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] 3282. 0/1 Knapsack 본문

SW_Expert

[SW Expert Academy] 3282. 0/1 Knapsack

코드와이 2021. 3. 25. 17:31

 

DP(Knapsack)

문제링크

swexpertacademy.com/main/code/problem/problemDetail.do?contestProbId=AWBJAVpqrzQDFAWr

 

SW Expert Academy

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

swexpertacademy.com

 

package D3;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;

public class knapsack_01 {

	public static void main(String[] args) throws NumberFormatException, 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("#").append(tc).append(" ");
			
			st = new StringTokenizer(br.readLine());
			int n = Integer.parseInt(st.nextToken());
			int k = Integer.parseInt(st.nextToken());
			int[][] NK = new int[n+1][2];
			
			for(int i = 1 ; i <= n; i++) {
				st = new StringTokenizer(br.readLine());
				
				NK[i][0] = Integer.parseInt(st.nextToken());
				NK[i][1] = Integer.parseInt(st.nextToken());
			}
			
			int[][] dp = new int[n+1][k+1];
			
			for(int i = 1 ; i <= n ; i++) {
				int cur_v = NK[i][0];
				int cur_c = NK[i][1];
				for(int j = 1 ; j <= k ; j++) {
					if(j >= cur_v) {
						dp[i][j] = Math.max(cur_c + dp[i-1][j-cur_v], dp[i-1][j]);
					} else {
						dp[i][j] = dp[i-1][j];
					}
				}
			}
			sb.append(dp[n][k]).append("\n");
		}
		sb.setLength(sb.length()-1);
		System.out.println(sb);
	}
}