Balanced Substring 873B

+describe:
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

题目大意:求最长区间a[L,R]且区间a满足0的个数q与1的个数p
相等,q=p

tip:得需要用stl里面的map,估计哈希表会MLT..

如果区间a[1,L-1]的前缀和dex1 , 区间b [1,R+1] 的前缀和dex2.
存在dex2 = dex1 则说明区间 c[L,R]内的元素和为0. 1+(-1) = 0.咦,要是我们把0变成-1,如果存在一个区间d[L,R]内的元素和为0则说明区间d是满足题目条件的.那么怎么找这个区间d? 首先区间我们得确定左区间和右区间,此处找的方法是枚举右区间R,当R=1、2、3、4…n的情况,左区间L呢? 这时候map就发挥了一个自动匹配左区间L的一个功能,如果当前的前缀和ans 能在map[ans] 找到(!!!map[前缀和] = 元素下标+1) ,则此时的左区间L = map[ans],如果不能找到,则存入map[ans] = 元素下标+1

coding

#include <iostream>
#include <cstdio>
#include <cmath>
#define N 1000010
using namespace std;

int mp[N];
int main(){
   int n ,ans = 0 ;
   cin >> n;
   for(int i = 0 ; i < n ; i++){
        int l,r;
        scanf("%d%d",&l,&r);
        mp[l] += 1;
        mp[r+1] -= 1;
   }

   int M = 0;
   for(int i = 0 ; i < N;i++){
       M +=mp[i];
       ans = max(M,ans);
   }
    cout << ans <<endl;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章