티스토리 뷰
// 알고리즘
1. dp
2. 배낭문제
3. dp배열 생성
- dp[N+1][maxCost]
- n값과 가장 높은비용의 배열 생성
4. 현재의 비용에서 가장 높은 메모리 저장
5. 문제에서 요구한 값보다 크거나 같은 비용이 나오면 정답
더보기
import java.util.*;
import java.io.*;
public class 앱_7579 {
static int N, M, arr[], cost[];
static class Point {
int m, c;
public Point(int m, int c) {
this.m = m;
this.c = c;
}
}
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine(), " ");
N = Integer.parseInt(st.nextToken());
M = Integer.parseInt(st.nextToken());
arr = new int[N];
cost = new int[N];
st = new StringTokenizer(br.readLine(), " ");
for (int i = 0; i < N; i++) {
arr[i] = Integer.parseInt(st.nextToken());
}
st = new StringTokenizer(br.readLine(), " ");
int cst = 0;
for (int i = 0; i < N; i++) {
int c = Integer.parseInt(st.nextToken());
cost[i] = c;
cst += c;
}
int[][] dp = new int[N + 1][cst + 1];
int ans = 0;
for (int i = 1; i <= N; i++) {
int memory = arr[i - 1];
int cnt = cost[i - 1];
for (int j = 0; j < dp[i].length; j++) {
if (j >= cnt) {
dp[i][j] = Math.max(dp[i - 1][j], dp[i - 1][j - cnt] + memory);
} else {
dp[i][j] = dp[i - 1][j];
}
}
}
for (int i = 0; i <= cst; i++) {
if (dp[N][i] >= M) {
ans = i;
break;
}
}
System.out.println(ans);
}
}
※ DP는 풀때마다 어려운거같다. 자주 풀어봐야할거같음
'Algorithm' 카테고리의 다른 글
알고리즘 감잡기 (1) | 2023.11.28 |
---|---|
프로그래머스_타켓 넘버 (0) | 2021.03.19 |
백준_행성 터널_2887 (0) | 2021.03.16 |
백준_비밀 모임_13424 (0) | 2021.03.12 |
백준_거의최단경로_5719 (0) | 2021.03.11 |