알고리즘

백준 12865번 평범한 배낭 (JAVA)

박카스마시며코딩 2023. 6. 26. 15:18

https://www.acmicpc.net/problem/12865

 

12865번: 평범한 배낭

첫 줄에 물품의 수 N(1 ≤ N ≤ 100)과 준서가 버틸 수 있는 무게 K(1 ≤ K ≤ 100,000)가 주어진다. 두 번째 줄부터 N개의 줄에 거쳐 각 물건의 무게 W(1 ≤ W ≤ 100,000)와 해당 물건의 가치 V(0 ≤ V ≤ 1,000)

www.acmicpc.net

 

저는 DP를 이용해 문제를 해결하였습니다.

저는 DP를 이용해 해당 depth와 무게일 때 최대 값어치를 저장하고 이를 활용하여 시간복잡도를 줄였습니다.

 

package BOJ.dp;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.StringTokenizer;
import java.util.function.Function;

public class BOJ_12865 {

    public static void main(String[] args) throws Exception {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        Function<String,Integer> stoi = Integer::parseInt;
        StringTokenizer st = new StringTokenizer(br.readLine());
        int n = stoi.apply(st.nextToken());
        int k = stoi.apply(st.nextToken());
        int[] weight = new int[n];
        int[] value = new int[n];
        int[][] dp = new int[n][k+1];
        for(int i = 0 ; i < n ; i++){
            Arrays.fill(dp[i],NOT_VALID);
            st = new StringTokenizer(br.readLine());
            weight[i] = stoi.apply(st.nextToken());
            value[i] = stoi.apply(st.nextToken());
        }
        int result = cal(0,0,weight,value,k,n,dp);
        System.out.println(result);
    }
    private static final int NOT_VALID = -1;
    private static int cal(int depth, int nowWeight,int[] weight, int[] value,int k,int n, int[][]dp) {
        if(depth == n){
            return 0;
        }
        if(dp[depth][nowWeight] != NOT_VALID){
            return dp[depth][nowWeight];
        }
        int result = 0;
        if(nowWeight + weight[depth] <= k){
             result = Math.max(result, cal(depth+1,nowWeight+weight[depth],weight,value,k,n,dp)+value[depth]);
        }
        result = Math.max(result, cal(depth+1,nowWeight,weight,value,k,n,dp));
        dp[depth][nowWeight] = result;
        return result;
    }
}