最長全1串

題目:給你一個01串,定義答案=該串中最長的連續爲1的長度,現在你有至多k次機會,每次機會可以將串中的某個0改成1,現在問最大可能答案。
輸入:

輸入第一行的兩個整數N,k,表示字符串長度和機會次數
第二行輸入N個整數,表示該字符串的元素
1
2
輸出

輸出一行表示答案
1
樣例輸入

10 2
1 0 0 1 0 1 0 1 0 1
1
2
樣例輸出

5
思路:

           先記錄下每個0的位置,然後以k長度從左往右滑動;

           每滑動一次就在兩頭分別設置一個指針,分別往左和往右,遇到第一個0便終止;

           從中取最大值。

#include <stdio.h>
#include <iostream>
#include<cstring>
#include <vector>
#include <assert.h>
#include <queue>
using namespace std;
#define MAX 300005
int arr[MAX];
int num[MAX];
int process(int n, int k, int numZ, int cnt){
    if(numZ <= k) return n;
    int top = 0;
    int ans = 0;

    for(; top<cnt; top++){
        int i = arr[top];

        int sum = top + k < cnt ? arr[top+k-1] - i + 1: n - i;
        for(int j = i - 1; j >= 0; j--){
            if(i <= 0) break;
            if(num[j]) sum++;
            else break;
        }
        //cout<<"#"<<i<<" l "<<sum<<endl;
        for(int j = top + k < cnt ? arr[top+k-1] + 1: n - i; j < n; j++){
            if(j == n-i ) break;
            if(num[j]) sum++;
            else break;
        }
        //cout<<"#"<<i<<" r "<<sum<<endl;
        ans = max(ans, sum);

    }

    return ans;
}
int main(){
    int n, k;

    cin>>n>>k;
    for(int i = 0; i < n; i++) cin>>num[i];
    int top = 0;
    int numZ = 0;
    for(int i = 0; i < n; i++){
        if(!num[i]){
            numZ ++;
            arr[top++]=i;
        }
    }
    cout<<process(n, k, numZ, top)<<endl;
    return 0;
}
/*
10 2
1 0 0 1 0 1 0 1 0 1
*/

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章