codeforces 660C C. Hard Process(二分)

时间:2022-12-19 16:32:04

题目链接:

C. Hard Process

time limit per test
1 second
memory limit per test
256 megabytes
input
standard input
output
standard 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


题意:

最多把k个0变成1,变完后连续的最长的全是1的串的长度是多少,并且输出最后得串;


思路:


用一个数组记录当前位一共有多少个0,暴力枚举最长串的最后一位,二分查找最长串的第一个1的位置;更新结果并记录好最长串的开始和结束位置,最后再输出就好啦;

AC代码:
/*
2014300227    660C - 5    GNU C++11    Accepted    93 ms    4388 KB
*/
#include <bits/stdc++.h>
using namespace std;
const int N=3e5+4;
typedef long long ll;
const double PI=acos(-1.0);
int n,a[N],k,b[N];
int check(int x,int y)
{
    if(b[y]-b[x-1]<=k)return 1;
    return 0;
}
int bis(int num)
{
    int l=1,r=num,mid;
    while(l<=r)
    {
        mid=(l+r)>>1;
        if(check(mid,num))r=mid-1;
        else l=mid+1;
    }
    return r+1;
}
int main()
{
    scanf("%d%d",&n,&k);
    for(int i=1;i<=n;i++)
    {
        scanf("%d",&a[i]);
        if(!a[i])b[i]=b[i-1]+1;
        else b[i]=b[i-1];
    }
    int ans=0,l=0,r=0;
    for(int i=1;i<=n;i++)
    {
        int fx=bis(i);
        if(i-fx+1>ans)
        {
            ans=i-fx+1;
            l=fx;
            r=i;
        }
    }
    printf("%d\n",ans);
    for(int i=1;i<=n;i++)
    {
        if(i>=l&&i<=r)
        {
            printf("1 ");
        }
        else printf("%d ",a[i]);
    }
    return 0;
}