a280中等後綴子集合和・可行性引導字典序還原

TOI 2021/06 潛力組:零

在仍有解的前提下優先填加號,找出字典序最小算式。

前往題目練習 →回報教學錯誤令 S≤10000。C++ 時間與空間 O(NS);Python 用整數位元集合,時間 O(NS/w)、空間 O(NS/w) 個機器字,另有 O(N) 還原。

解題思路

設全部數字總和 S。若加號側總和為 P、減號側總和為 S−P,要等於 0 必須 P=S/2;第一個數字固定在加號側。因此 S 必須為偶數,且後 N−1 個數字中要選出總和 S/2−a₁ 的子集合。

從右往左建立 suffix[i],表示 a[i] 到末尾可以選出的所有總和。空後綴只能湊 0;每加入 x,就把原集合與所有值加 x 的集合聯集。還原時若選當前數字作加號後,剩下目標仍可由下一個後綴湊出,就選 +;否則選 −。每一步保留至少一個可行完成法,且在第一個可分歧處優先 +,因此得到字典序最小答案。

Step-by-step animation

範例 [15,29,14],後綴加號目標為 14

回報動畫錯誤
步驟 1 / 3

檢查總和

總和 58,一側需要 29;第一個 15 已固定為正,還需 14。

15
29
14
target
29−15=14

Reference solution

回報程式錯誤

完整程式

#include <iostream>
#include <vector>
#include <numeric>
#include <string>
using namespace std;
int main() {
    int n;
    cin >> n;
    vector<int> a(n);
    for (int &x : a)
        cin >> x;
    int sum = accumulate(a.begin(), a.end(), 0), target = sum / 2 - a[0];
    if (sum % 2 || target < 0) {
        cout << 0 << '\n';
        return 0;
    }
    vector<vector<unsigned char>> suffix(n + 1, vector<unsigned char>(sum + 1));
    suffix[n][0] = 1;
    for (int i = n - 1; i >= 1; --i)
        for (int s = 0; s <= sum; ++s)
            suffix[i][s] = suffix[i + 1][s] || (s >= a[i] && suffix[i + 1][s - a[i]]);
    if (!suffix[1][target]) {
        cout << 0 << '\n';
        return 0;
    }
    cout << 1 << '\n' << a[0];
    for (int i = 1; i < n; ++i) {
        if (target >= a[i] && suffix[i + 1][target - a[i]]) {
            cout << '+' << a[i];
            target -= a[i];
        } else
            cout << '-' << a[i];
    }
    cout << '\n';
}

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

更多