【CodeForces - 660C】Hard Process (尺取 或 二分+滑窗,前缀和预处理)
題干:
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 1Output
4 1 0 0 1 1 1 1Input
10 2 1 0 0 1 0 1 0 1 0 1Output
5 1 0 0 1 1 1 1 1 0 1題目大意:
給定一個數組?a,含有?n?個元素。數組?a?中的每個元素要么是?0,要么是?1?。輸入一個n,一個k,然后第二行是數組。
讓我們假定,數組?a?中,僅由數字 1 組成的連續元素所構成的子分段,其最長的長度為?f(a)。您可以將不超過?k?個 0 更改為 1,使得?f(a)?最大化。
解題報告:
? ?這題做法多樣,可以nlogn二分長度然后遍歷。還有一種方法是o(n)尺取,但是感覺難寫一點?
AC代碼:
#include<cstdio> #include<cstring> #include<algorithm> #include<iostream> #define ll long long using namespace std; const int MAX = 3e5 + 5; int n,k; int a[MAX],sum[MAX];bool ok(int len) {for(int i = 1; i+len-1<=n; i++) {if(sum[i+len-1] - sum[i-1] >= len-k) return 1;}return 0; } int main() {cin>>n>>k;for(int i = 1; i<=n; i++) scanf("%d",a+i),sum[i] = sum[i-1] + a[i];int l = 0,r = n;int mid = (l+r)/2;while(l<r) {mid = (l+r+1)/2;if(ok(mid)) l=mid;else r=mid-1;}printf("%d\n",l);for(int i = 1; i+l-1<=n; i++) {if(sum[i+l-1] - sum[i-1] >= l-k) {for(int j = 1; j<=n; j++) {if(j < i || j > i+l-1) printf("%d",a[j]);else printf("1");if(j != n) putchar(' ');}return 0 ;}}return 0 ;}總結:
? 注意這題是二分求最大值,所以需要mid=(l+r+1)/2調節一下。最后還是l是我們需要的。
總結
以上是生活随笔為你收集整理的【CodeForces - 660C】Hard Process (尺取 或 二分+滑窗,前缀和预处理)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 电视没人买了:今年出货将暴跌近500万台
- 下一篇: 【 HRBUST - 1055】Sing