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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值