[Zhengqing] [1895] 985's 0-1 String Challenge

Problem Description

985的0-1串难题
Time limit: 1 SecMemory limit: 128 MB

Description

985 has a 0-1 string of length n. It is known that he can modify it at most k times (each modification flips one character, i.e. 0->1 or 1->0). He wants to know the maximum length of a contiguous all-1 substring he can obtain.

Input

The first line contains an integer t, representing t test cases.
The first line of each test case contains two integers n and k, representing the above information.
Note: 1 <= t <= 12, 1 <= n <= 100000, 0 <= k <= 100000.

Output

An integer representing the maximum length that can be obtained.

Sample Input

1
2
3
4
5
2
6 3
010100
6 2
010100

Sample Output

1
2
5
4

Problem Analysis

Yu Shen:
Solution 1: Observe that the final answer is linear, so we use Binary Search on the Answer and turn the problem into a decision problem.
For the current binary-search value mid, check its validity: whether there exists a contiguous segment of length mid such that the total number of 0 characters in that segment is <= k.
Time complexity: O(T * n * log(n)).
Solution 2: Consider dp, where dp[i] represents the optimal contiguous segment starting at the i-th character.
Then we only need to find the largest j (i <= j <= n) such that the total number of 0 characters in [i, j] is <= k.
We can first compute the Prefix Sum of 0 characters, and then binary search each time. The final answer is max(dp[i]) (1 <= i <= n).
Time complexity: O(T * n * log(n)).

Noob:
Record how many 0s there are between 0 and i and store it in cnt[i]
Then the interval [n, m] contains a[m] - a[n-1] zeros
The length (number of characters) is n-m+1
So compare k with a[m] - a[n-1] to perform interval updates
and record the maximum length seen as the result

cpp
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include<stdio.h> 
#include<algorithm> 
using namespace std; 
char s[100200]; 
int cnt[100200]; 
int main() { 
    int T; 
    scanf("%d",&T); 
    while(T--) { 
        int n,k; 
        scanf("%d %d",&n,&k); 
        scanf("%s",s); 
        cnt[0]=(s[0]=='0'?1:0); 
        for(int i=1; i<n; i++) { 
            cnt[i]=cnt[i-1]; 
            if(s[i]=='0') 
                cnt[i]++; 
        } 
        if(cnt[n-1]<=k) 
            printf("%d\n",n); 
        else { 
            int l=0,res=0; 
            for(int i=0; i<n; i++) { 
                while(k<cnt[i]-(l==0?0:cnt[l-1])) 
                    l++; 
                res=max(res,i-l+1); 
            } 
            printf("%d\n",res); 
        } 
    } 
    return 0; 
} 

Problem link: [1895]985’s 0-1 String Problem

Loading...