https://swexpertacademy.com/main/code/problem/problemDetail.do?contestProbId=AWT-lPB6dHUDFAVT
SW Expert Academy
SW 프로그래밍 역량 강화에 도움이 되는 다양한 학습 컨텐츠를 확인하세요!
swexpertacademy.com
import java.util.*;
import java.io.*;
public class Test {
static int N, L;
static int[][] materials;
static boolean[] isSelected;
static ArrayList<Integer> result;
public static void powerSet (int cnt) {
if (cnt == N) {
int tasteSum = 0;
int calSum = 0;
for (int i = 0; i < N; i++) {
if (isSelected[i]) {
tasteSum += materials[i][0];
calSum += materials[i][1];
}
}
if (calSum < L) // 제한 칼로리 미만일 경우
result.add(tasteSum);
return;
}
isSelected[cnt] = true;
powerSet(cnt + 1);
isSelected[cnt] = false;
powerSet(cnt + 1);
}
public static void main (String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
int T = Integer.parseInt(st.nextToken());
for (int t = 1; t <= T; t++) {
st = new StringTokenizer(br.readLine(), " ");
N = Integer.parseInt(st.nextToken()); // 재료의 수
L = Integer.parseInt(st.nextToken()); // 제한 칼로리
materials = new int[N][2];
for (int n = 0; n < N; n++) {
st = new StringTokenizer(br.readLine(), " ");
materials[n][0] = Integer.parseInt(st.nextToken()); // 재료의 맛에 대한 점수
materials[n][1] = Integer.parseInt(st.nextToken()); // 재료의 칼로리
}
isSelected = new boolean[N];
result = new ArrayList<>();
powerSet(0);
int max = 0;
for (int i = 0; i < result.size(); i++)
max = Math.max(max, result.get(i));
System.out.println("#" + t + " " + max);
}
}
}
코드가 많이 길고 복잡해 보이지만
순열, 조합, 부분집합의 재귀를 이용한 알고리즘을 배워서
부분집합의 알고리즘을 이용해 풀어보았습니다.
'Algorithm > 백준+프로그래머스+SWEA+정올+구름' 카테고리의 다른 글
[Algorithm] 백준 16935 배열 돌리기3 (0) | 2021.08.15 |
---|---|
[Algorithm] 백준 2563 색종이 (0) | 2021.08.14 |
[Algorithm] SWEA 6808 규영이와 인영이의 카드게임 (0) | 2021.08.13 |
[Algorithm] 백준 2961 도영이가 만든 맛있는 음식 (0) | 2021.08.12 |
[Algorithm] 백준 3040 백설공주와 일곱난쟁이 (0) | 2021.08.12 |