1. 程式人生 > 其它 >【二分】Hard Process

【二分】Hard Process

題目連結 --> https://codeforces.com/contest/660/problem/C

題目描述

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

題目大意

  • 給定一個 n 表示01陣列的長度
  • 改變其中的不超過k個0
  • 使得這個序列中連續的1的長度達到最長
  • 輸出最長長度並輸出改變後的序列

思路及程式碼實現

使用二分的思想,列舉每個可能的左端點,二分右端點,逐個比較,直到找到最長的連續的1的序列,並不斷記錄更新最長連續序列的起點下標和終點下標

C++程式碼實現

#include <iostream>
#include <algorithm>
using namespace std;
typedef pair<int, int> PII;

const int N = 3e5 + 10;
int n, k;
int s[N], a[N];

int main(){
    cin >> n >> k;
    for (int i = 1; i <= n; i++){
        scanf("%d", &a[i]);
        s[i] = s[i - 1] + (a[i] == 0);
    }
    PII ans = {0, 0};
    int res = 0;
    // int l, r, mid;
    for (int i = 1; i <= n; i++){
        int l = i, r = n;
        while (l <= r){
            int mid = (l + r) >> 1;
            if (s[mid] - s[i - 1] <= k){
                if (mid - i + 1 > res){            //注意二分的邊界問題
                    res = mid - i + 1;        
                    ans.first = i, ans.second = mid;
                }
                l = mid + 1;
            }
            else    r = mid - 1;
        }
    }
    cout << res << endl;
    for (int i = 1; i <= n; i++){
        if (i >= ans.first && i <= ans.second)
            cout << 1 << ' ';
        else
            cout << a[i] << ' ';
    }
    cout << endl;
    return 0;
}
/*

7 1
1 0 0 1 1 0 1

4
1 0 0 1 1 1 1

*/