codeforces 2016-2017 NTUWFTSC J Zero Game

本文介绍了一种利用贪心算法和单调队列解决字符串中最大连续零问题的方法。通过计算前缀和并使用单调队列优化过程,实现了高效求解在限定操作次数下字符串的最大连续零序列长度。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

You are given one string S consisting of only '0' and '1'. You are bored, so you start to play with the string. In each operation, you can move any character of this string to some other position in the string. For example, suppose . Then you can move the first zero to the tail, and S will become '0100'.

Additionally, you have Q numbers K1, K2, ..., KQ. For each i, you wonder what can be the maximum number of consecutive zeroes in the string if you start with S and use at most Ki operations. In order to satisfy your curiosity, please write a program which will find the answers for you.

Input

The first line of input contains one string S. The second line of input contains one integer Q. Each of the following Q lines contains one integer Ki indicating the maximum number of operations in i-th query.

  • 2 ≤ N ≤ 106
  • the length of S is exactly N characters
  • S consists of only '0' and '1'
  • 1 ≤ Q ≤ 105
  • N × Q ≤ 2 × 107
  • 1 ≤ Ki ≤ 106
Output

For each query, output one line containing one number: the answer for this query.

Example
input
0000110000111110
5
1
2
3
4
5
output
5
8
9
9
9
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

贪心+单调队列+思路~

我们先求一个前缀和a[i]表示到i为止的1的个数。

枚举区间[l+1,r],首先区间要满足a[r]-a[l]<=k,然后,我们会把区间所有的1都取走,然后用剩余步数尽量多地放0进来,所以答案就是(r-l-(a[r]-a[l]))+(k-(a[r]-a[l]))=(r-2*a[r])-(l-2*a[l])+k,对于每一个位置i我们记录f[i]=i-2*a[i],这样每次用f[r]-f[l]更新答案,最后再+k即可。

这样计算的话,有的时候已经没有0可以挪入区间了,所以我们最后ans=min(ans,n-a[n]),确保不会出现非法情况。

ans有可能<0,所以ans=max(ans,0)。

单调队列的写法很神奇,见代码!


#include<cstdio>
#include<cstring>
#include<iostream>
using namespace std;

int n,m,k,a[1000001],f[1000001],q[1000001],he,ta,ans;
char s[1000001];

int read()
{
	int x=0,f=1;char ch=getchar();
	while(ch<'0' || ch>'9') {if(ch=='-') f=-1;ch=getchar();}
	while(ch>='0' && ch<='9') {x=(x<<1)+(x<<3)+ch-'0';ch=getchar();}
	return x*f;
}

int main()
{
	scanf("%s",s+1);n=strlen(s+1);
	for(int i=1;i<=n;i++) a[i]=a[i-1]+(s[i]=='1');
	for(int i=1;i<=n;i++) f[i]=i-2*a[i];
	m=read();
	while(m--)
	{
		k=read();he=1;ta=0;ans=-1e7;
		for(int i=0,j=0;i<=n;i++)
		{
			while(j<=n && a[j]-a[i]<=k)
			{
				while(he<=ta && f[j]>=f[q[ta]]) ta--;
				q[++ta]=j++;
			}
			while(he<=ta && q[he]<=i) he++;
			if(he<=ta) ans=max(ans,f[q[he]]-f[i]);
		}
		ans+=k;
		ans=max(ans,0);ans=min(ans,n-a[n]);
		printf("%d\n",ans); 
	}
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值