题解:CF1579F Array Stabilization (AND version)

· · 题解

思路

观察题目,不难发现,如果序列中有一个 0,那么这个 0 移动后无论在哪个位置,这个位置一定也会变为 0,所以可以把题目理解成,每次将序列中的 0 右移 d 位,问多少次可以用 0 覆盖掉序列中的所有 1,bfs 即可。

代码

#include<bits/stdc++.h>

using namespace std;

const int MAXN = 1e6 + 1;

int n, d, T, ans, a[MAXN], b[MAXN], h = 1, t;
void bfs() {
    while(h <= t) {
        int len = t - h + 1;
        for(int i = 1; i <= len; i++) {
            int x = b[h++], y = (x + d) % n; 
            if(a[y] > 0) {
                b[++t] = y, a[y] = 0;
            }
        }
        ans++;
    }
}

int main() {
    ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
    cin >> T;
    while(T--) {
        ans = 0;
        cin >> n >> d;
        for(int i = 0; i < n; i++) {
            cin >> a[i];
        }
        for(int i = 0; i < n; i++) {
            if(a[i] == 0) {
                b[++t] = i;
            }
        }
        bfs();
        for(int i = 0; i < n; i++) {
            if(a[i] != 0) {
                ans = -1;
            }
        }
        cout << ans - (ans != -1) << "\n";
    }
    return 0;
}