PAT甲級真題 1068 Find More Coins (30) C++實現(0-1揹包,找最小序列的方法)

題目

Eva loves to collect coins from all over the universe, including some other planets like Mars. One day she visited a universal shopping mall which could accept all kinds of coins as payments. However, there was a special requirement of the payment: for each bill, she must pay the exact amount. Since she has as many as 104 coins with her, she definitely needs your help. You are supposed to tell her, for any given amount of money, whether or not she can find some coins to pay for it.

Input Specification:

Each input file contains one test case. For each case, the first line contains 2 positive numbers: N (<=104, the total number of coins) and M(<=102, the amount of money Eva has to pay). The second line contains N face values of the coins, which are all positive numbers. All the numbers in a line are separated by a space.

Output Specification:

For each test case, print in one line the face values V1 <= V2 <= … <= Vk such that V1 + V2 + … + Vk = M. All the numbers must be separated by a space, and there must be no extra space at the end of the line. If such a solution is not unique, output the smallest sequence. If there is no solution, output “No Solution” instead.

Note: sequence {A[1], A[2], …} is said to be “smaller” than sequence {B[1], B[2], …} if there exists k >= 1 such that A[i]=B[i] for all i < k, and A[k] < B[k].

Sample Input 1:
8 9
5 9 8 7 2 3 4 1
Sample Output 1:
1 3 5
Sample Input 2:
4 8
7 2 4 3
Sample Output 2:
No Solution

思路

屬於經典0-1揹包問題(每個幣最多選一次),物品重量和價值均爲幣值a[i],把問題轉化成使用這些幣值在總價值m範圍內所能組合出的最大價值,若該最大價值=m則有解,若最大價值<m則無解。

關鍵點是爲了求最小序列,可先將幣值降序排列,每次找到新的相等的最優解時都採用,這就保證了較小的幣值總能被選中。

使用動態規劃法。用F[i][j]表示用前i個幣在總價值不超過j時能達到的最大價值。若最後F[n][m] = m,則表示有解;若F[n][m] < m,則表示無解。

若選擇了第i個幣,則當前最大總價值爲F[i-1][j-a[i]] + a[i];若不選擇第i個幣,則當前最大總價值等於F[i-1][j]。

寫出遞推方程:
F[i][0] = 0
F[0][j] = 0
F[i][j] = max{ F[i-1][j], F[i-1][j-a[i]] + a[i] }

F[i][j]只需保存最新一組值,可使用一維數組F[j]代替,每輪遍歷都覆蓋上一輪的F[j]。

設置標記函數B[i][j],記錄取得最大價值時是否選用了第i個幣,可以追溯出解的選取序列。它不能用一維數組取代,因爲前面輪次的值還要在追溯過程中使用。

易錯點

真正實現代碼時還是出現了很多錯誤。

循環體計算方向

一開始寫的循環體判斷條件如下,有什麼不對呢?

   for (int i=1; i<=n; i++) {
        for (int j=1; j<=m; j++){
            if (a[i]<=j && (F[j-a[i]]+a[i])>=F[j] && (F[j-a[i]]+a[i])<=j){
				...
            }
            else{
                ...
            }
        }
    }

分析:第3行比較F[j-a[i]]+a[i]) 和 F[j]大小時,F[j-a[i]]可能是本輪已更新過的值而非預期的上一輪的值,兩個值同時更新的話相當於把a[i]選了兩遍,所以就出錯了。

解決方法:把第二層循環倒着來就能避免上述問題;另外F[j-a[i]]+a[i]<=j的判斷條件沒必要加,因爲在a[i] <= j時這個判斷恆成立。代碼修改爲:

    for (int i=1; i<=n; i++) {
        for (int j=m; j>=1; j--){  //此處計算方向改成從大到小
            if (j>=a[i] && F[j-a[i]]+a[i] >= F[j]) {
				...
            }
            else{
                ...
            }
        }
    }

標記函數的記錄和追溯

標記函數以及追溯解的代碼一開始這樣寫的:

    for (int i=1; i<=n; i++) {
        for (int j=m; j>=1; j--){
            if (j>=a[i] && F[j-a[i]]+a[i] >= F[j]) {
                F[j] = F[j-a[i]] + a[i];
                B[i][j] = a[i];  //直接記錄選取的值
            }
            else{
                B[i][j] = B[i-1][j];
            }
        }
    }
    if (F[m] != m){
        cout << "No Solution";
    }
    else{
        int v = B[n][m];
        cout << v;
        while (1){
            n--;
            m -= v;
            v = B[n][m];
            if (v==0){
                break;
            }
            cout << " " << v;
        }
    }

分析:測試點2無法通過。找了大半天問題發現,上面解的追溯過程中n的變化(n- -)是沒有道理的,相應的解的記錄方法也應該修改。

解決方法:記錄每次選擇的標號i,比如B[5][5] = 3,表示前5個幣中選擇不大於5的最優選擇是第3個,表示比第3個大的沒有被選,下次應該追溯B[2][5-a[3]]。n的正確變化應該是n = B[n][m] - 1:

    for (int i=1; i<=n; i++) {
        for (int j=m; j>=1; j--){
            if (j>=a[i] && F[j-a[i]]+a[i] >= F[j]) {
                F[j] = F[j-a[i]] + a[i];
                B[i][j] = i;  //此處應記錄選擇的編號
            }
            else{
                B[i][j] = B[i-1][j];
            }
        }
    }
    if (F[m] != m){
        cout << "No Solution";
    }
    else{
        int v = a[B[n][m]];
        cout << v;
        while (1){
            n = B[n][m] - 1;  //注意此處不是n--
            m -= v;
            v = a[B[n][m]];  //本輪選的數
            if (v==0){
                break;
            }
            cout << " " << v;
        }
    }

終於AC

終於AC了,淚流滿面…

代碼

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

bool cmp(int &a1, int &a2){
    return a1 > a2;
}
int main(){
    int n, m;
    cin >> n >> m;
    vector<int> a(n+1);
    for (int i=1; i<=n; i++){
        cin >> a[i];
    }
    sort(a.begin()+1, a.end(), cmp);
    //動態規劃,第i輪的F[j]表示用前i個幣在總價值不超過j時能達到的最大價值
    vector<int> F(m+1);
    //記錄選擇
    vector<vector<int> > B(n+1, vector<int>(m+1));
    for (int i=1; i<=n; i++) {
        for (int j=m; j>=1; j--){
            if (j>=a[i] && F[j-a[i]]+a[i] >= F[j]) {
                F[j] = F[j-a[i]] + a[i];
                B[i][j] = i;
            }
            else{
                B[i][j] = B[i-1][j];
            }
        }
    }
    if (F[m] != m){
        cout << "No Solution";
    }
    else{
        int v = a[B[n][m]];
        cout << v;
        while (1){
            n = B[n][m] - 1;
            m -= v;
            if (m==0){
                break;
            }
            v = a[B[n][m]];  //本輪選的數
            cout << " " << v;
        }
    }
    return 0;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章