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;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章