b320中等

96 臺北市資訊學科能力競賽(2007)|錄製專輯

在恰裝滿CD時最大化歌曲數並計排列方式。

解題思路

在恰裝滿CD時最大化歌曲數並計排列方式。

dp[s]存恰好大小s可達的最多歌曲數,ways[s]存達此最多數量的子集合數;初值dp[0]=0、ways[0]=1,其餘不可達。

每首歌從S向下更新;新數量更大就取代並複製方式數,相同就加總。選或不選當前歌曲的子集合互斥,所以計數無重複。

若S不可達輸出0 0;否則每個最多L首的子集合有L!種排列,最終K=ways[S]×L!。

時間 O(NS)次大整數操作,空間 O(S+N);另計K的位數成本。

Step-by-step animation

精確裝滿的最多歌曲與計數逐步追蹤

回報動畫錯誤
步驟 1 / 3

步驟 1

10、50、30、70、60,容量80。

恰裝滿80
步驟
1

Reference solution

回報程式錯誤

完整程式

#include <bits/stdc++.h>
#include <boost/multiprecision/cpp_int.hpp>
using namespace std;
using boost::multiprecision::cpp_int;
using ll = long long;
int main() {
    int n;
    cin >> n;
    vector<int> a(n);
    for (int &x : a)
        cin >> x;
    int S;
    cin >> S;
    vector<int> d(S + 1, -1000);
    vector<cpp_int> w(S + 1);
    d[0] = 0;
    w[0] = 1;
    for (int x : a)
        for (int s = S; s >= x; s--)
            if (d[s - x] >= 0) {
                int v = d[s - x] + 1;
                if (v > d[s]) {
                    d[s] = v;
                    w[s] = w[s - x];
                } else if (v == d[s])
                    w[s] += w[s - x];
            }
    if (d[S] < 0)
        cout << "0 0\n";
    else {
        cpp_int z = w[S];
        for (int i = 2; i <= d[S]; i++)
            z *= i;
        cout << d[S] << ' ' << z << '\n';
    }
}

先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。

更多