L3-001 凑零钱

#include <bits/stdc++.h>

using namespace std;

using pii = pair<int, int>;

const int N = 10010, M = 110;

int f[M];
int n, m;
int w[N];
int pre[N];
bool g[N][M];

int main() {
    cin >> n >> m;
    for (int i = 1; i <= n; i++) {
        cin >> w[i];
    }
    sort(w + 1, w + n + 1, [&](int a, int b) { 
        return a > b;
    });
    
    for (int i = 1; i <= n; i++) {
        for (int j = m; j >= w[i]; j--) {
            if (f[j] <= f[j - w[i]] + w[i]) {
                g[i][j] = true;
                f[j] = f[j - w[i]] + w[i];
            }  
        }
    }

    if (f[m] != m) cout << "No Solution" << "\n";
    else {
        vector<int> res;
        int i = n, j = m;
        while (i >= 1 && j) {
            if (g[i][j]) {
                int t = i;
                res.push_back(w[t]);
                j -= w[t];
            }
            i--;
        }
        for (int k = 0; k < res.size(); k++) {
            cout << res[k] << " "[k == res.size() - 1];
        }
    }

    return 0;
}

posted @ 2022-04-18 21:54  Xxaj5  阅读(44)  评论(0编辑  收藏  举报