L3-001 湊零錢


  附上題目鏈接:https://www.patest.cn/contests/gplt/L3-001

  

韓梅梅喜歡滿宇宙到處逛街。現在她逛到了一家火星店里,發現這家店有個特別的規矩:你可以用任何星球的硬幣付錢,但是絕不找零,當然也不能欠債。韓梅梅手邊有104枚來自各個星球的硬幣,需要請你幫她盤算一下,是否可能精確湊出要付的款額。

輸入格式:

輸入第一行給出兩個正整數:N(<=104)是硬幣的總個數,M(<=102)是韓梅梅要付的款額。第二行給出N枚硬幣的正整數面值。數字間以空格分隔。

輸出格式:

在一行中輸出硬幣的面值 V1 <= V2 <= ... <= Vk,滿足條件 V1 + V2 + ... + Vk = M。數字間以1個空格分隔,行首尾不得有多余空格。若解不唯一,則輸出最小序列。若無解,則輸出“No Solution”。

注:我們說序列{A[1], A[2], ...}比{B[1], B[2], ...}“小”,是指存在 k >= 1 使得 A[i]=B[i] 對所有 i < k 成立,並且 A[k] < B[k]。

 

分析:我們可以使用01背包來解決這個問題, 可以知道用的錢幣數越多則字典序越少, 用的錢幣數相同的情況下后面的錢幣越大那么字典序越小, 因此我們將錢幣升序排列, 定義dp[j]為組成j所需要的錢幣數。 代碼如下:

PS:這種方法有bug, 新的方法請大家最下面。感謝@cacyth指出錯誤

#include <cstdio>
#include <cstring>
#include <algorithm>
#include <vector>

using namespace std;
const int inf = 0x3f3f3f3f;
int N, M;
int a[10000 + 100];
int dp[10000 + 100];
int pre[10000 + 100];
vector<int> res;

int main() {
    scanf("%d%d", &N, &M);
    for(int i=1; i<=N; i++) scanf("%d", &a[i]);
    sort(a+1, a+1+N);
    for(int i=0; i<=M; i++) dp[i] = -inf;
    dp[0] = 0;
    for(int i=1; i<=N; i++) {
        for(int j=M; j-a[i]>=0; j--)
        if(dp[j] <= dp[j-a[i]] + 1) {
            dp[j] = dp[j-a[i]] + 1;
            pre[j] = j-a[i];
        }
    }
    if(dp[M] <= 0)
        printf("No Solution\n");
    else {
        int now = M;
        while(now != 0) {
            res.push_back(now - pre[now]);
            now = pre[now];
        }
        for(int i=res.size()-1; i>=0; i--)
            printf("%d%c", res[i], i==0?'\n':' ');
    }
    return 0;
}

   

新思路:我們考慮將物品按照價值降序排列, 然后一次往背包里面加, 對於一個容量的背包, 只要后面的物品加進去那么他的字典序就會減少, 代碼如下:

#include <cstdio>
#include <cstring>
#include <algorithm>
#include <vector>

using namespace std;
int N, M;    //硬幣個數
int value[10000 + 100];
int dp[1000];
int path[10000+2][100 + 10];

bool cmp(const int &a, const int &b) {
    return a > b;
}

int main() {
    scanf("%d%d", &N, &M);
    for(int i=0; i<N; i++)
        scanf("%d", &value[i]);
    sort(value, value+N, cmp);
    memset(path, 0, sizeof(path));
    memset(dp, 0, sizeof(dp));
    dp[0] = 1;

    for(int i=0; i<N; i++) {
        for(int j=M; j>=0; j--) {
            if(j-value[i]>=0 && dp[j-value[i]]==1) {
                dp[j] = 1;
                path[i][j] = 1;
            }
        }
    }

    //printf("print res\n");
    if(dp[M] == 0)
        printf("No Solution\n");
    else {
        vector<int> res;
        int i=N-1, j = M;
        while(i>=0 && j>0) {
            if(path[i][j] == 1) {
                res.push_back(value[i]);
                j -= value[i];
            }
            i -= 1;
        }
        sort(res.begin(), res.end());
        for(int i=0; i<res.size(); i++) {
            printf("%d%c", res[i], i==res.size()-1?'\n':' ');
        }
    }
    return 0;
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM