์‹ค๋ฒ„1 : ๋™์  ๊ณ„ํš๋ฒ• ๋ฌธ์ œ์ด๋‹ค.

์ƒ๊ฐ

๋‹ค์ด๋‚˜๋ฏน์˜ ์œ ํ˜• ์ค‘ ์ค‘์š”ํ•œ ์œ ํ˜•์ด๋‹ค. ๋Œ€๋ถ€๋ถ„์˜ ๋™์ „ ๋ฌธ์ œ์˜ ๋ฐฉ์‹๊ณผ ๋น„์Šทํ•˜๋‹ค. 1์ฐจ์› ๋‹ค์ด๋‚˜๋ฏน์ด์ง€๋งŒ 2๊ฐœ์˜ ๋ฐ˜๋ณต๋ฌธ์„ ํ†ตํ•ด 2์ฐจ์› ์ฒ˜๋Ÿผ ์ƒ๊ฐํ•˜๋Š” ๊ฒƒ์ด ํ•„์š”ํ•˜๋‹ค.

์ •์˜

dp[i] = n์˜ ๊ฐ€์น˜๋ฅผ ๋งŒ๋“ค๊ธฐ ์œ„ํ•ด ํ•„์š”ํ•œ ์ตœ์†Œ ์ˆซ์ž์˜ ๊ฐœ์ˆ˜

์ •์˜๋Š” ๋งค์šฐ ๊ฐ„๋‹จํ•˜๋‹ค. ํ•˜์ง€๋งŒ ์ด ๊ฒƒ์„ ๊ตฌํ˜„ํ•  ๋•Œ๋Š” 2์ฐจ์› ์ฒ˜๋Ÿผ ์ƒ๊ฐํ•ด์•ผ ํŽธํ•˜๋‹ค.

์ ํ™”์‹

dp[j] = min(dp[j],dp[j-a[i]]+1)

์œ„์˜ ์ ํ™”์‹์ด ๋‚˜์˜ค๋Š” ๊ณผ์ •์„ ์ƒ๊ฐํ•ด๋ณด์ž.

3 15
2
5
10

========๋™์ „์˜ ๊ฐ’ : 2========
0 - 1 - 2 - 3 - 4 - 5 - 6 - 7

========๋™์ „์˜ ๊ฐ’ : 5========
0 - 1 - 2 1 3 2 4 3 2 4 3 5 4

========๋™์ „์˜ ๊ฐ’ : 10========
0 - 1 - 2 1 3 2 4 3 1 4 2 5 3

  1. 2๋กœ์จ ๋งŒ๋“ค ์ˆ˜ ์žˆ๋Š” ๊ฒƒ์„ ์—…๋ฐ์ดํŠธ ํ•œ๋‹ค.
  2. 5๋กœ์จ ๋งŒ๋“ค ์ˆ˜ ์žˆ๋Š” ๊ฒƒ์„ ์—…๋ฐ์ดํŠธ ํ•œ๋‹ค.
  3. 10๋กœ์จ ๋งŒ๋“ค ์ˆ˜ ์žˆ๋Š” ๊ฒƒ์„ ์—…๋ฐ์ดํŠธ ํ•œ๋‹ค.

์ด ๋•Œ, ํ•ด๋‹น ๊ฐ€์น˜๊ฐ€ ์—…๋ฐ์ดํŠธ ๋˜๋Š” ๋ฐฉํ–ฅ์€ ๊ฒฐ์ •๋˜์–ด ์žˆ๋‹ค. 5์˜ ๊ฐ€์น˜๋Š” 3์˜ ๊ฐ€์น˜์—์„œ 2์˜ ๋™์ „์„ ๋”ํ•ด์„œ ๋งŒ๋“ค ์ˆ˜ ์žˆ๋‹ค. ์ด๋Ÿฐ ๊ด€๊ณ„๋ฅผ ์ž˜ ์—ฎ๋Š”๋‹ค๋ฉด ๋ฌธ์ œ๋ฅผ ํ•ด๊ฒฐํ•  ์ˆ˜ ์žˆ๋‹ค.

Code

#include<iostream>
#include<vector>
#include<string>
#include<cstring>
#include<cmath>
#include<algorithm>
using namespace std;
int N, M;
int a[101];
int dp[10001];
const int INF = 987654321;
 
void print(int coin){
    cout << "========" << "๋™์ „์˜ ๊ฐ’ : "<< coin << "========" << '\n';
    for (int i = 0; i < M; i++) {
        if (dp[i] == INF) {
            cout << '-' << " ";
        } else cout << dp[i] << " ";
    }cout << '\n' << '\n';
}
 
int main(){
    cin >> N >> M;
    for (int i = 1; i <= N; i++) {
        cin >> a[i];
    }
 
    fill(dp+1, dp+M+1, INF);
 
    for (int i = 1; i <= N; i++) {
        for (int j = a[i]; j <= M; j++) {
            dp[j] = min(dp[j],dp[j-a[i]]+1);
        }
        print(a[i]);
    }
    if (dp[M] == INF) cout << -1;
    else cout << dp[M];
    cout << '\n';
    return 0;
}

Reference