873B

来源:互联网 发布:大数据的影响因素 编辑:程序博客网 时间:2024/05/29 03:45

You are given a string s consisting only of characters0 and 1. A substring[l, r] of s is a string slsl + 1sl + 2...sr, and its length equals tor - 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 ins.

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

Output

If there is no non-empty balanced substring ins, print 0. Otherwise, print the length of the longestbalanced substring.

Example
Input
811010111
Output
4
Input
3111
Output
0

求最长的[l,r]使得区间[l,r]中的0和1的个数相等。思路:把0变为-1如果0~i的和与0~j的和相等,则说明i和j之间存在相同数量的1、-1.记录位置求出最大的区间

思路最腻害.....

#include<bits/stdc++.h>using namespace std;const int maxn=1e5+10;map<int,int>m;char s[maxn];int a[maxn];int main(){    int n;    while(~scanf("%d%s",&n,s+1))    {        m.clear();        for(int i=1;i<=n;i++)        {            if(s[i]=='0')                a[i]=-1;            else a[i]=1;        }        int sum=0;        int ans=0;        for(int i=1;i<=n;i++)        {            ans+=a[i];            if(ans!=0){            if(m[ans])                sum=max(sum,i-m[ans]);            else m[ans]=i;            }            else sum=max(sum,i);        }        printf("%d\n",sum);    }}


原创粉丝点击