๊ณจ๋“œ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;
}

Reference