영원히 남는 기록, 재밌게 쓰자

SWEA [5215] 햄버거 다이어트 D3 본문

Algorithm/SWEA

SWEA [5215] 햄버거 다이어트 D3

youngjae-kim 2024. 2. 16. 11:45
728x90
반응형
 

SW Expert Academy

SW 프로그래밍 역량 강화에 도움이 되는 다양한 학습 컨텐츠를 확인하세요!

swexpertacademy.com

 

풀이

- 제한 칼로리 이상은 결과에 포함시키지 않는다.

- 제한 칼로리 이하이고 맛에 대한 점수가 더 높다면 최종 점수를 갱신한다.

- 모든 부분 집합을 구하면서 위 두가지 과정을 반복한다.

 

재귀함수를 통해 구현할 수 있었다.

 

- 부분 집합을 고른 횟수를 세기 위해 cnt 변수를 사용하였다.

- cnt(부분 집합을 고른 횟수)가 곧 맛점수 배열과 칼로리 배열의 인덱스이므로 포함한 경우와 포함하지 않은 경우를 계속 탐색하기 위해
재귀함수를 포함하지 않으면 cnt만 증가하는 방식으로 진행해주었다.

 

풀이코드

package com.swea.D3.p5215;

import java.io.*;
import java.util.*;

public class Solution {
    static int[] taste, cal;
    static int N, L, maxScore;

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringBuilder sb = new StringBuilder();

        int T = Integer.parseInt(br.readLine());

        for (int t = 1; t <= T; t++) {
            sb.append("#" + t + " ");

            StringTokenizer st = new StringTokenizer(br.readLine(), " ");

            N = Integer.parseInt(st.nextToken());
            L = Integer.parseInt(st.nextToken());

            taste = new int[N];
            cal = new int[N];
            maxScore = 0;

            for (int i = 0; i < N; i++) {
                st = new StringTokenizer(br.readLine(), " ");

                taste[i] = Integer.parseInt(st.nextToken());
                cal[i] = Integer.parseInt(st.nextToken());

            }

            combination(0, 0, 0);

            sb.append(maxScore + "\n");
        }

        System.out.println(sb);
    }

    private static void combination(int cnt, int tstScore, int calories) {

        if (calories > L) {
            return;
        }

        if (cnt == N) { // 부분 집합이 완성되면
            if (calories <= L) {
                maxScore = Math.max(tstScore, maxScore);
            }
            return;
        }

        // 부분 집합에 포함하는 경우
        combination(cnt + 1, tstScore + taste[cnt], calories + cal[cnt]);

        // 부분 집합에 포함하지 않는 경우
        combination(cnt + 1, tstScore, calories);
    }
}
728x90
반응형