跳到正文

题解

题解:CF2126B No Casino in the Mountains

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

文章信息

收录
2025年12月12日
更新
2025年12月12日
篇幅
约 2 分钟
题目
CF2126B

版本

  1. v1当前

思路


首先,利用 lastlast 表示最后一个 11 出现的地方,由此算出每个连续的0串,我把它存到了 num[]num[] 中。


然后推出关键句:

ans+=⌊s/k⌋ans += \lfloor s / k \rfloor

其中设连续的0串长度为 ss, 答案数量为 ansans 。不难发现需要分类讨论。


  1. 当 ss << kk 时,ansans 不需要更改。
  2. 当 ss == kk 时,ansans 要加 11。
  3. 当 ss == kk 时, 需要额外分析一下。

由题意得:每两个连续 kk 个 0串间需要有一个格外的0, 我们可以把 kk 个0串与额外的一个0组合起来。 所以

ans+=⌊s/k⌋ans += \lfloor s / k \rfloor

应改为:

ans+=⌊s/(k+1)⌋ans += \lfloor s / (k + 1) \rfloor

但每次计算的末尾的一组少了一个0,所以需要补上,所以最终的关键语句(主要思想)为

ans+=⌊(s+1)/(k+1)⌋ans += \lfloor (s + 1) / (k + 1) \rfloor

时间复杂度:O(n)O(n)


其他细节注释在AC代码中。

C++
#include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 5;
int t;
int n, k;
int a[N];
int num[N], cnt = 0, f = 0, ans = 0;
int main() {
	cin >> t;
	while (t--) {
		int last = 0, ans = 0;
		cnt = 0;
		cin >> n >> k;
		a[n + 1] = 1; //防止出现整个01串只有0导致num数组存储错误的情况
		for (int i = 1; i <= n; i++) cin >> a[i];
		for (int i = 1; i <= n + 1; i++) {
			if (a[i] == 1) {
				 num[cnt++] = i - 1 - last;
				 last = i;
			}
		}
		for (int i = 0; i < cnt; i++) {
			int x = num[i];
			if (x < k) continue;
			else if (x == k) ans++;
			else {
				ans += (x + 1) / (k + 1); // 注意这行代码
			}
		}
		cout << ans << endl;
	}
	return 0;
}
原文