코드와이
[SW Expert Academy] 5215. 햄버거 다이어트 본문
문제링크
swexpertacademy.com/main/code/problem/problemDetail.do?contestProbId=AWT-lPB6dHUDFAVT
풀이방법1 : 재귀
package D3;
import java.util.Scanner;
public class 햄버거_다이어트 {
static int N;
static int limit;
static int[] score;
static int[] cal;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int T = sc.nextInt();
for (int tc = 1; tc <= T; tc++) {
N = sc.nextInt();
limit = sc.nextInt();
score = new int[N];
cal = new int[N];
for ( int i = 0; i < N; i++) {
score[i] = sc.nextInt();
cal[i] = sc.nextInt();
}
sel = new boolean[N];
ans = 0;
hamburger(0,0,0);
System.out.println("#" + tc + " " + ans);
}
}
static boolean[] sel;
static int ans = 0;
static void hamburger(int idx, int sumCal, int sumScore) {
if (sumCal > limit) {
return;
}
if (sumScore > ans) {
ans = sumScore;
}
if (idx == N) {
return;
}
hamburger(idx + 1, sumCal + cal[idx], sumScore + score[idx]);
hamburger(idx + 1, sumCal, sumScore);
}
}
풀이방법2 : bit mask
package D3;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class 햄버거_다이어트2 {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st;
StringBuilder sb = new StringBuilder();
int T = Integer.parseInt(br.readLine());
for (int tc = 1; tc <= T; tc++) {
sb.append("#" + tc + " ");
st = new StringTokenizer(br.readLine());
int N = Integer.parseInt(st.nextToken());
int limit = Integer.parseInt(st.nextToken());
int[] score = new int[N];
int[] cal = new int[N];
for ( int i = 0; i < N; i++) {
st = new StringTokenizer(br.readLine());
score[i] = Integer.parseInt(st.nextToken());
cal[i] = Integer.parseInt(st.nextToken());
}
int ans = 0;
int sum_s, sum_c;
for(int i = 0 ; i < Math.pow(2, N) ; i++) {
sum_s = 0;
sum_c = 0;
for(int j = 0 ; j < N ; j++) {
if( (i & (1 << j)) > 0) {
sum_s += score[j];
sum_c += cal[j];
}
if(sum_c > limit) {
break;
}
if(ans < sum_s) ans = sum_s;
}
}
sb.append(ans);
System.out.println(sb);
sb.setLength(0);
}
}
}
'SW_Expert' 카테고리의 다른 글
[SW Expert Academy] 1767. [SW Test 샘플문제] 프로세서 연결하기 (0) | 2021.02.26 |
---|---|
[SW Expert Academy] 1231. [S/W 문제해결 기본] 9일차 - 중위순회 (0) | 2021.02.22 |
[SW Expert Academy] 1222.[S/W 문제해결 기본] 6일차 - 계산기1 (0) | 2021.02.15 |
[SW Expert Academy] 1224. [S/W 문제해결 기본] 6일차 - 계산기3 (0) | 2021.02.15 |
[SW Expert Academy] 8457. 알 덴테 스파게티 (0) | 2021.02.15 |