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;
}
}
'알고리즘' 카테고리의 다른 글
프로그래머스 콜라츠 수열 (JAVA) (0) | 2023.06.28 |
---|---|
프로그래머스 글자 지우기(JAVA) (0) | 2023.06.27 |
프로그래머스 더 맵게 (JAVA) (0) | 2023.06.25 |
프로그래머스 문자열 겹쳐쓰기 (JAVA) (0) | 2023.06.24 |
백준 2839번 설탕 배달 (JAVA) (0) | 2023.06.23 |