๊ณจ๋3 : ๋์ ๊ณํ๋ฒ ๋ฌธ์ ์ด๋ค.
์๊ฐ
์ด ๋ฌธ์ ๋, BOJ - ํ๋ฒํ ๋ฐฐ๋ญ(12865)๊ณผ ๋งค์ฐ ๋น์ทํ๋ค. ํ๋ฒ ํธ๋ ๊ฒ์ด ์ข๋ค.
์ด ๋ฌธ์ ๋ memory์ ๋ฒ์๊ฐ ๋งค์ฐ ํฌ๊ธฐ ๋๋ฌธ์, ์ด ๊ฒ์ ๊ธฐ์ค์ผ๋ก ๋ก์ง์ ์ง๋ฉด ๋ฉ๋ชจ๋ฆฌ๊ฐ ํฐ์ง๋ค. ๊ทธ๋์ ๋ฐ๋๋ก cost๋ฅผ ์ด๋ค ๊ธฐ์ค์ผ๋ก ๋ง๋ค ์ ์๋ ์ง๋ฅผ ๊ณ ๋ฏผํ์ฌ ์ฝ๋๋ฅผ ์งฐ๋ค.
์ ์
dp[i][j] = i๋ฒ์งธ ์ฑ๊น์ง ๋นํ์ฑํํ์ ๋ j์ ๋น์ฉ๊น์ง ๋ง๋ค ์ ์์ ๋ ๋ฉ๋ชจ๋ฆฌ์ ์ต๋๊ฐ
๋ฉ๋ชจ๋ฆฌ์ ์ต๋๊ฐ์ด๋ผ ์ก์ ์ด์ ๋, ์ต์ Cost๋ก ์ต๋ ๋ฉ๋ชจ๋ฆฌ๋ฅผ ์ง์ฐ๋ ๊ฒ์ด ํฉ๋ฆฌ์ ์ด๊ธฐ ๋๋ฌธ์ด๋ค.
5 60
30 10 20 35 40
3 0 3 5 4
ํ์ฌ ๋น์ฉ : 3 ํ์ฌ ๋ฉ๋ชจ๋ฆฌ : 30
0 0 0 30 30 30 30 30 30 30 30 30 30 30 30 30
ํ์ฌ ๋น์ฉ : 0 ํ์ฌ ๋ฉ๋ชจ๋ฆฌ : 10
10 10 10 40 40 40 40 40 40 40 40 40 40 40 40 40
ํ์ฌ ๋น์ฉ : 3 ํ์ฌ ๋ฉ๋ชจ๋ฆฌ : 20
10 10 10 40 40 40 60 60 60 60 60 60 60 60 60 60
ํ์ฌ ๋น์ฉ : 5 ํ์ฌ ๋ฉ๋ชจ๋ฆฌ : 35
10 10 10 40 40 45 60 60 75 75 75 95 95 95 95 95
ํ์ฌ ๋น์ฉ : 4 ํ์ฌ ๋ฉ๋ชจ๋ฆฌ : 40
10 10 10 40 50 50 60 80 80 85 100 100 115 115 115 135
6
์๋ก์ด ์ฑ์ด ์ถ๊ฐ๋จ์ ๋ฐ๋ผ, ๊ทธ Cost์์ ๊ฐ์ง ์ ์๋ ๋ฉ๋ชจ๋ฆฌ์ ์ต๋๊ฐ์ ๊ฐ์ง๊ณ ์์ผ๋ฉด ๋ฌธ์ ๋ ํด๊ฒฐ๋๋ค.
์ ํ์
dp[j] = max(temp[j], temp[j-nowCost] + nowMem)
temp๋ i-1๊ฐ์ ์ฑ์ ์ฌ์ฉํ์ ๋์ ์ ๋ณด๋ฅผ ๊ฐ๊ณ ์๋ dp์ด๋ค. ์ด์ ํ๋ฒํ ๋ฐฐ๋ญ ๋ฌธ์ ์์๋ ์ด์ depth์ ์ ๋ณด๋ง์ ๊ฐ์ ธ๋ค๊ฐ ์ฌ์ฉํ๊ธฐ ๋๋ฌธ์ ๋ฉ๋ชจ๋ฆฌ๊ฐ ๋ญ๋น๋๋ค.
์ด ๋ฌธ์ ๋, ์๋ก์ด ์ฑ์ด ์ถ๊ฐ๋์์ ๋, ํ์ฌ Cost์์ ์ต๋ ๋ฉ๋ชจ๋ฆฌ๋ฅผ ์ง์ฐ๋ ๊ฒ์ ๋ชฉํ๋ก ์ฝ๋๋ฅผ ์ง๋ฉด ๋๋ค.
Code
#include<iostream>
#include<vector>
#include<string>
#include<cstring>
#include<iomanip>
#include<cmath>
#include<algorithm>
#include<queue>
#define COSTMAX 10000
#define APPMAX 100
using namespace std;
typedef long long ll;
int costLimit = 0;
int N, M;
ll dp[COSTMAX+1];
ll temp[COSTMAX+1];
int mem[APPMAX+1];
int cost[APPMAX+1];
ll ans;
void print(int i){
cout << "ํ์ฌ ๋น์ฉ : " << cost[i] << " ํ์ฌ ๋ฉ๋ชจ๋ฆฌ : " << mem[i] << '\n';
for (int i = 0; i <= costLimit; i++) {
cout << setw(3) << dp[i] << " ";
}cout << '\n' << '\n';
}
int main(){
cin >> N >> M;
for (int i = 1; i <= N; i++) {
cin >> mem[i];
}
for (int i = 1; i <= N; i++) {
cin >> cost[i];
costLimit += cost[i];
}
for (int i = 1; i <= N; i++) {
memcpy(temp, dp, sizeof(dp));
int nowCost = cost[i];
int nowMem = mem[i];
for (int j = nowCost; j <= costLimit; j++) {
dp[j] = max(temp[j], temp[j-nowCost] + nowMem);
}
print(i);
}
for (int i = 0; i <= costLimit; i++) {
if (dp[i] >= M) {
ans = i;
break;
}
}
cout << ans << '\n';
return 0;
}