C. Hard Process
time limit per test1 second
memory limit per test256 megabytes
inputstandard input
outputstandard output
You are given an array a with n elements. Each element of a is either 0 or 1.
Let’s denote the length of the longest subsegment of consecutive elements in a, consisting of only numbers one, as f(a). You can change no more than k zeroes to ones to maximize f(a).
Input
The first line contains two integers n and k (1 ≤ n ≤ 3·105, 0 ≤ k ≤ n) — the number of elements in a and the parameter k.
The second line contains n integers ai (0 ≤ ai ≤ 1) — the elements of a.
Output
On the first line print a non-negative integer z — the maximal value of f(a) after no more than k changes of zeroes to ones.
On the second line print n integers aj — the elements of the array a after the changes.
If there are multiple answers, you can print any one of them.
Examples
input
7 1
1 0 0 1 1 0 1
output
4
1 0 0 1 1 1 1
input
10 2
1 0 0 1 0 1 0 1 0 1
output
5
1 0 0 1 1 1 1 1 0 1
题目链接
http://codeforces.com/problemset/problem/660/C
题目大意
由n个数组成数字串,这些数不是0就是1,可以把其中k个0改为1,要使得连续的1最多,输出最多能有多少个连续的1,同时输出改变后的数字串。
数据范围
(1 ≤ n ≤ 3·1e5, 0 ≤ k ≤ n)
ai (0 ≤ ai ≤ 1)
解题思路
1.模拟每一次改变,每次进行对比。多开一个数组标记将0改1的位置,再用一个数组记住当前最优解,知道0改1的位置后就能每次进行还原。
但是这个方法复杂度高,写起来麻烦,而且容易超时,第一次在test10超时了,进行多次优化后在test15又超时了。
2.只需要用变量来记改变的左、右端,不需要直接对原数组进行改变。每次将0变1,只要左端释放前一个将0变1的数,右边再加上一个就行。
小技巧
计算多少个连续1的个数,只要拿改变的区间外后数第一个0前的非0下标减区间前数第一个0的下标就能得到答案
对比了一下网上的二分法和尺取法,发现尺取法更加简单,而且复杂度更低,只要O(N),以后要注重思维培养。
解决代码
#include<iostream>
#include<cstdio>
#include<algorithm>
using namespace std;
int main()
{
int n,k,a[300005],cnt = 0,ans = 0,l = 1,r = 1,ll,rr,check = 0;
cin >> n >> k;
for(int i = 1; i <= n;i++){
cin >> a[i];
}
while(r <= n){
while(check <= k&&r <= n){
if(a[r] == 0){
if(check == k) break;
else check++;
}
r++;
}
if(r - l > ans){
rr = r - 1;
ll = l;
ans = r - l;
}
while(l <= n&&a[l] == 1){
++l;
}
l++;
check--;
}
printf("%d\n",ans);
for(int i = 1;i <= n;i++){
if(i >= ll&&i <= rr)printf("1");
else printf("%d",a[i]);
if(i < n) printf(" ");
}
return 0;
}