codeforces 2016-2017 NTUWFTSC J Zero Game

来源:互联网 发布:迅龙数据恢复下载安装 编辑:程序博客网 时间:2024/06/06 07:38

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
0000110000111110512345
output
58999
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

贪心+单调队列+思路~

我们先求一个前缀和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;}

原创粉丝点击