Notice
Recent Posts
Recent Comments
Link
«   2024/11   »
1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
Tags
more
Archives
Today
Total
관리 메뉴

코드와이

[SW Expert Academy] 5215. 햄버거 다이어트 본문

SW_Expert

[SW Expert Academy] 5215. 햄버거 다이어트

코드와이 2021. 2. 16. 18:48

 

문제링크

swexpertacademy.com/main/code/problem/problemDetail.do?contestProbId=AWT-lPB6dHUDFAVT

 

SW Expert Academy

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

swexpertacademy.com

 

풀이방법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);
			
			
		}
	}
}