Balanced Substring CodeForces - 873B(思维+前缀和)

本文介绍了一种高效算法,用于解决寻找给定二进制字符串中最长平衡子串的问题。平衡子串指0和1数量相等的子串。通过使用前缀和与哈希表(map)相结合的方法,该算法能在O(n)时间内找到最长平衡子串的长度。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >



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.

Example
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.

思路:这个题一开始没思路,会暴力,知道肯定会超时,后来听说用前缀和,1是1,0变成-1,那么如果发现两个点的前缀和是一样的,那么这个区间肯定-1,1个数相同,即1,0个数相同,以此找最大长度,然后就写,发现我擦,从确定前缀和的一个点找下一个相同的这不还得用n^2的时间吗?

后来看网上才发现如此巧妙的把n^2时间优化成n,用一个map,利用map不能重复插入的原则,第一个插入的一定是第一次出现的,那么一次遍历,如果在遇到这个值,直接求长度就可以了,妙啊

最后注意前缀和为0的情况,看代码注释

code:

#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include <map>
using namespace std;
int n;
string s;
int a[101000];
map<int,int>k;//优化时间的关键
int main(){
    int i,j;
    cin >> n >> s;//输入字符串
    for(i = 0; s[i]; i++){
        if(s[i]=='1')a[i+1] = 1;
        else a[i+1] = -1;//将字符串转化成int数组
    }
    int sum = 0;
    int ans = 0;
    for(i = 1; i <= n; i++){
        sum += a[i];
        if(k[sum]){
            ans = max(ans,i-k[sum]);//如果之前存在过这个和,现在又出现了,说明这个区间1,0个数是相同的,相减为长度
        }
        else k[sum] = i;//利用map不能重复插入的特性,所以如果存在一定是这个值第一次出现时的位置,所以这样后面再出现就相减求区间长度On复杂度求出
        if(sum==0){
            ans = max(ans,i);//如果前缀和出现零一定说明从一开始就是1,0个数相同,否则前缀和一定不可能为零
        }
    }
    cout << ans << endl;
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值