b691困難

雙色的禁整除子集合

在任兩數和禁整除條件下,選到兩色且最大化位置數。

解題思路

數值只需看模 M 的餘數。非自補的一組 {r,M−r} 中不能同時選兩側,但同側任意兩數都相容。固定選某側且需要其具有的顏色時,多選該側所有位置不會破壞條件,故只考慮全選左、全選右、全不選。

自補餘數0及偶數M的M/2最多只能選一個位置,可依存在的顏色選一個。各互補組之間完全相容,用4個顏色覆蓋狀態(空、色0、色1、兩色)做最大選取數 DP,最後取兩色狀態。這比單純每組取較多側多了必要的全域兩色約束。

時間 O(n+M),空間 O(M),Python 輸入緩衝 O(n);每組至多三種選擇與4個狀態。

Step-by-step animation

逐步教學推演:依各步描述的例子觀察狀態、轉移與答案。

回報動畫錯誤
步驟 1 / 3

互補組

M=4,餘數1有兩個色0,餘數3有一個色1。

1:2個色0
3:1個色1
可同選兩側
否

Reference solution

回報程式錯誤

完整程式

#include <bits/stdc++.h>
using namespace std;
using ll = long long;
const ll MOD = 1000000007;
int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    int n, M;
    cin >> n >> M;
    vector<array<int, 2>> f(M);
    while (n--) {
        int a, c;
        cin >> a >> c;
        f[a % M][c]++;
    }
    array<int, 4> d{0, -1000000000, -1000000000, -1000000000};
    for (int r = 0; r <= M / 2; r++) {
        int s = (M - r) % M;
        vector<pair<int, int>> v{{0, 0}};
        if (r == s) {
            for (int c = 0; c < 2; c++)
                if (f[r][c])
                    v.push_back({1 << c, 1});
        } else
            for (int k : {r, s})
                v.push_back({(f[k][0] ? 1 : 0) | (f[k][1] ? 2 : 0), f[k][0] + f[k][1]});
        array<int, 4> nd;
        nd.fill(-1000000000);
        for (int a = 0; a < 4; a++)
            for (auto [b, c] : v)
                nd[a | b] = max(nd[a | b], d[a] + c);
        d = nd;
    }
    cout << (d[3] < 0 ? -1 : d[3]) << '\n';
}

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

更多