CodeForces - 873B Balanced Substring

B. Balanced Substring
time limit per test
1 second
memory limit per test
256 megabytes
input
standard input
output
standard output

You are given a string s consisting only of characters 0 and 1. A substring [l, r] of s is a string slsl + 1sl + 2... sr, and its length equals to r - l + 1. A substring is called balanced if the number of zeroes (0) equals to the number of ones in this substring.

You have to determine the length of the longest balanced substring of s.

Input

The first line contains n (1 ≤ n ≤ 100000) — the number of characters in s.

The second line contains a string s consisting of exactly n characters. Only characters 0 and 1 can appear in s.

Output

If there is no non-empty balanced substring in s, print 0. Otherwise, print the length of the longest balanced substring.

Examples
input
8
11010111
output
4
input
3
111
output
0
Note

In the first example you can choose the substring [3, 6]. It is balanced, and its length is 4. Choosing the substring [2, 5] is also possible.

In the second example it's impossible to find a non-empty balanced substring.




题目大意:字符串是由0和1组成,求字符串的最长子串,使0和1的数目相同


记录0和1的个数,然后当两个个数相同的情况下,进行暴力,求最大值

ps:还要注意整个字符串为平衡串的情况

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 

using namespace std;

typedef long long ll;

map mp;

int main() {
    int n;
    char s[1000001];
    
    int ans = 0;
    int x = 0;
    int y = 0;
    
    cin >> n;
    cin >> s;
    
    
    for(int i = 0;i < n;i++) {
        if(s[i] == '1') {  
            x++;  
        }  
        else y++;  
        if(mp.count(y-x)) {  
            ans = max(ans, i-mp[y-x]);  
        }  
        else {  
            mp[y-x] = i;  
        }  
    }    
    if(x == y) {
        ans = n;
    }
    cout << ans << endl;
    
    return 0;  
}






你可能感兴趣的:(STL)