Educational Codeforces Round 30

来源:互联网 发布:浙大网新恒天软件福利 编辑:程序博客网 时间:2024/05/22 13:53

B. Balanced Substring

time limit per test1 second
memory limit per test256 megabytes
inputstandard input
outputstandard 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.

题意:给你一个n和一个长度为n的字符串(只包含01),问你求一个最长的区间使得区间里0的个数等于1的个数

分析: 因为看到连续这个关键字,一直往Two Pointers 这边想,结果就GG了,一早看见解题发现好坑呀,直接利用map的“BUG”轻松过:首先定义‘0’的话就记做-1,‘1’还是记做1,先用一个r变量来记录前缀和,只要“前缀和”没出现过,记录下坐标,只要出现过,更新下答案,这个思想就像是一个二次函数,到达同一个y值,因为该y值到顶的高度一定一样,所以其区间和比为零,这样应该形象点吧,在不懂的,直接手算模拟下就OK啦

参考代码

#include<bits/stdc++.h>using namespace std;string s;int n;map<int,int> m;int main(){    ios_base::sync_with_stdio(0);    cin>>n>>s;    m[0] = -1;    int ans = 0,r = 0;    for(int i = 0; i < n; i++)    {        r += s[i] == '1'?1:-1;        if(m.count(r)) ans = max(ans,i-m[r]);        else m[r] = i;    }    cout<<ans<<endl;    return 0;}
  • 如有错误或遗漏,请私聊下UP,thx
原创粉丝点击