【CodeForces】660C - Hard Process(二分,尺取法)

本文介绍了一道关于数组中寻找最长连续子段的问题,并提供了一种有效的解决方案。通过使用额外的数组来记录0的数量,结合二分查找和滑动窗口的思想,实现了在限定次数内将0转换为1以最大化连续1的长度。

点击打开题目

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



很好的一个二分法的题。

首先用一个sum数组储存到当前节点0的个数,然后用一个 for 循环从第一个数(不包括)开始尺取,依次更新结果就行了。


代码如下:

#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
int num[300000+11];
int sum[300000+11] = {0};		//在当前节点0的个数 
int main()
{
	int n,k;
	int pos;
	int l,st,endd;		//长度,起点,终点(闭区间) 
	while (~scanf ("%d %d",&n,&k))
	{
		memset (sum,0,sizeof (sum));
		for (int i = 0 ; i < n ; i++)
		{
			scanf ("%d",&num[i]);
			if (num[i])
				sum[i] = sum[i-1];
			else
				sum[i] = sum[i-1] + 1;
		}
		//首先先计算从第一个数开始的结果
		pos = upper_bound (sum , sum + n , k) - 1 - sum;
		l = pos + 1;
		st = 0;
		endd = pos;
		//然后计算左开右闭区间的最优解
		for (int i = 0 ; i < n ; i++)
		{
			pos = upper_bound (sum , sum + n , sum[i] + k) - 1 - sum;
			if (pos - i > l)
			{
				l = pos - i;
				st = i + 1;
				endd = pos;
			}
		}
		//最后输出
		for (int i = st ; i <= endd ; i++)
			num[i] = 1;
		printf ("%d\n",l);
		for (int i = 0 ; i < n ; i++)
			printf ("%d ",num[i]);
		printf ("\n");
	}
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值