20250909 baekjoon

This commit is contained in:
songyc macbook 2025-09-09 21:27:46 +09:00
parent 69ebe99a4c
commit 7b38665087
2 changed files with 66 additions and 0 deletions

View File

@ -0,0 +1,44 @@
#include <stdio.h>
#include <stdlib.h>
int max(int a, int b) {
return a>b ? a : b;
}
int main() {
int N, K;
scanf("%d %d",&N, &K);
int** items = (int**)malloc(sizeof(int*)*(N+1));
int** dp = (int**)malloc(sizeof(int*)*(N+1));
for(int i=0; i<=N; i++) {
items[i] = (int*)malloc(sizeof(int)*2);
if(i==0) {
items[i][0] = 0;
items[i][1] = 0;
}
else {
scanf("%d %d",&items[i][0], &items[i][1]);
}
dp[i] = (int*)malloc(sizeof(int)*(K+1));
for(int j=0; j<=K; j++) dp[i][j] = 0;
}
for(int n=1; n<=N; n++) {
for(int k=1; k<=K; k++) {
if (items[n][0] <= k) dp[n][k] = max(dp[n-1][k], dp[n-1][k-items[n][0]] + items[n][1]);
else dp[n][k] = dp[n-1][k];
}
}
printf("%d\n",dp[N][K]);
for(int i=0; i<=N; i++) {
free(items[i]);
free(dp[i]);
}
free(items);
free(dp);
return 0;
}

View File

@ -0,0 +1,22 @@
if let input1 = readLine(), let NK = input1.split(separator: " ").compactMap({Int($0)}) as? [Int],
let N = NK.first, let K = NK.last
{
var items: [[Int]] = []
for _ in 0..<N {
if let input2 = readLine(), let rows = input2.split(separator: " ").compactMap({Int($0)}) as? [Int] {
items.append(rows)
}
}
var dp: [[Int]] = Array(repeating: Array(repeating: 0, count: K+1), count: N+1)
for n in 1...N {
for k in 1...K {
if items[n-1][0] <= k {
dp[n][k] = max(dp[n-1][k], dp[n-1][k-items[n-1][0]] + items[n-1][1])
}
else {
dp[n][k] = dp[n-1][k]
}
}
}
print(dp[N][K])
}