跳到正文

题解

题解:CF1579F Array Stabilization (AND version)

bananamilktea约 2 分钟
原文
文章信息与版本

文章信息

发布
2024年6月13日
收录
2025年12月12日
更新
2026年10月9日
篇幅
约 2 分钟
题目
CF1579F

版本

  1. v1当前

思路

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

代码

C++
#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;
}
原文