https://www.acmicpc.net/problem/16194
16194번: 카드 구매하기 2
첫째 줄에 민규가 구매하려고 하는 카드의 개수 N이 주어진다. (1 ≤ N ≤ 1,000) 둘째 줄에는 Pi가 P1부터 PN까지 순서대로 주어진다. (1 ≤ Pi ≤ 10,000)
www.acmicpc.net
저는 해당 문제를 DP를 활용하여 문제를 해결하였습니다.
해당 DP[depth] = 카드를 살 수 있는 수가 depth만큼 남았을때 최소 값을 가지게 하였습니다.
package BOJ.DP;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
import java.util.function.Function;
public class BOJ_16194 {
private static final int INF = 987_654_321;
private static int dfs(int depth, int[] input,int[] dp){
if(depth < 0){
return INF;
}
if(depth == 0){
return 0;
}
if(dp[depth] != 0){
return dp[depth];
}
int result = INF;
for(int i = depth ; i > 0 ; i--){
int share = depth / i;
for(int j = 1; j <= share ; j++){
result = Math.min(result, dfs(depth - i * j,input,dp) + j * input[i]);
}
}
dp[depth] = result;
return result;
}
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine()," ");
Function<String,Integer> stoi = Integer::parseInt;
int n = stoi.apply(st.nextToken());
int[] input = new int[n+1];
int[] dp = new int[n+1];
st = new StringTokenizer(br.readLine()," ");
for(int i = 1 ; i <= n ; i++){
input[i] = stoi.apply(st.nextToken());
}
System.out.println(dfs(n,input,dp));
}
}
'알고리즘' 카테고리의 다른 글
프로그래머스 신고 결과 받기(JAVA) (0) | 2022.02.20 |
---|---|
백준 17141번 연구소 2 (JAVA) (0) | 2022.02.19 |
백준 15591번 MooTube (JAVA) (0) | 2022.02.17 |
백준 2661번 좋은수열 (JAVA) (0) | 2022.02.15 |
백준 16929번 Two Dots (JAVA) (0) | 2022.02.14 |