跳到正文

题解

题解:P12350 「HCOI-R2」光影

lovely_firefly约 1 分钟
原文
文章信息与版本

文章信息

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

版本

  1. v1当前

分析完题目后,容易想到贪心,每次合并两个中间 00 的数量最小的“ 1 块”,而每次合并肯定会减少一个“ 1 块”。正确性显然。

步骤:

· 先遍历一遍 ss ,在这个过程中统计有多少个“ 1 块”,保存进 ansans ;还要统计有多少个之间隔了 ii 个 00 的“ 1 块”,把这个数量保存进 cnt[i]cnt[i] 。

· 从 11 到 10710^7 遍历 cntcnt 数组,如果能合并就合并, ans−1ans-1 。

最后献上我码风独特的代码:

C++
#include <iostream>
#include <queue>
using namespace std;
const int N=1e7+3;
int n,k,cnt[N];
char s[N];
int main()
{
	scanf("%d%d%s",&n,&k,s+1);
	int lst=-1,ans=0;
	for (int i=1;i<=n;++i)
	{
		if (s[i]=='1')
		{
			if (lst<i-1)
			{
				++ans;
				if (lst!=-1) ++cnt[i-lst-1];
			}
			lst=i;
		}
	}
	for (int i=1;i<=1e7;++i)
	{
		while (k>=i && cnt[i])
			k-=i,--ans,--cnt[i];
	}
	printf("%d",ans);
	return 0;
}
原文