A.Balanced Substring
您将得到一个仅由字符0和1组成的字符串s。s的子串[l, r]是一个字符串slsl + 1…sr,其长度等于r - l + 1。如果0的个数等于子串中1的个数,则称为平衡子串。请确定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
分析:题目要求求出最长平衡串,属于前缀和+思维题,我们让0标识为-1(可以当处理01串的一个思路)这样我们判断求出所有位置的前缀和,贪心求出最大长度即可
#include<bits/stdc++.h>
using namespace std;
typedef long long ll ;
const int N = 1e5 + 10;
ll a[N];
ll sum[N];
string s;
ll vis[N * 2 + 10]; //向后移动的时候标记数组要开足够大
int n;
int main()
{
memset (vis , -1 , sizeof vis);
cin >> n;
cin >> s;
for (int i = 1; i <= n; i ++)
{
if(s[i - 1] == '0') a[i] = -1;
else a[i] = 1;
}
for (int i = 1; i <= n; i ++ ) sum[i] = sum[i - 1] + a[i];
ll ans = -1;
for(int i = 0; i <= n; i ++)
{
if (vis[sum[i] + n] == -1) vis[sum[i] + n] = i; 标记出现位置
else ans = max (ans , i - vis[sum[i] + n]); 再次出现就dp
}
这里调试有点问题的,我们把整个判断向后移n位dp结果不变,不移就会wa不太明白
if (ans == -1) cout << 0 << endl;
else cout << ans << endl;
return 0;
}