https://www.acmicpc.net/problem/14916
14916번: 거스름돈
첫째 줄에 거스름돈 액수 n(1 ≤ n ≤ 100,000)이 주어진다.
www.acmicpc.net
저는 해당 문제를 DP를 이용하여 문제를 해결하였습니다.
처음에는 break를 사용하지 않아 시간이 2초가 살짝 넘었습니다.
돈을 5원짜리 먼저 그리고 for문도 제일 큰 값에서 줄여나가는 식으로 하여 가장 먼저 값을 찾을 때가 제일 동전의 개수가 적기 때문에 INF가 아니면 바로 break를 해 1초 안에 돌아가도록 하였습니다.
package BOJ.DP;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.function.Function;
public class BOJ_14916 {
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
Function<String,Integer> stoi = Integer::parseInt;
int n = stoi.apply(br.readLine());
int[] dp = new int[n+1];
int result = dfs(0,n,dp);
if(result == INF){
System.out.println(-1);
}else{
System.out.println(result);
}
}
private static int[] money = {5,2};
private static final int INF = 987654321;
private static int dfs(int depth, int n, int[] dp) {
if(dp[n] != 0){
return dp[n];
}
if(depth == 2 && n != 0){
return INF;
}
if(n == 0){
return 0;
}
int result = INF;
for(int i = n / money[depth] ; i >= 0 ; i--){
result = Math.min(result,dfs(depth+1,n - money[depth] * i,dp) + i);
if(result != INF){
break;
}
}
dp[n] = result;
return result;
}
}
'알고리즘' 카테고리의 다른 글
백준 1944번 복제 로봇 (JAVA) (0) | 2022.03.19 |
---|---|
백준 2568번 전깃줄 - 2 (JAVA) (0) | 2022.03.19 |
백준 14465번 소가 길을 건너간 이유5 (JAVA) (0) | 2022.03.17 |
백준 7662번 이중 우선순위 큐 (JAVA) (0) | 2022.03.16 |
백준 1715번 카드 정렬하기 (JAVA) (0) | 2022.03.16 |