51Nod_1393 0和1相等串
http://www.51nod.com/Challenge/Problem.html#!#problemId=1393
题目
给定一个0-1串,请找到一个尽可能长的子串,其中包含的0与1的个数相等。
输入
一个字符串,只包含01,长度不超过1000000。
输出
一行一个整数,最长的0与1的个数相等的子串的长度。
样例输入
1011
样例输出
2
分析
使用前缀和,前缀和pre[i].val表示01字符串前i个字符中,1的数量-0的数量的值。因此问题就是求满足1的数量-0的数量=0的最大区间,程序使用排序进行优化,具体看程序。
C++程序
#include<iostream>
#include<algorithm>
#include<map>
#include<string>
using namespace std;
const int N=1000005;
struct Node{
int val,pos;
//以值为第一关键字,位置为第二关键字,从小到大排序
bool operator< (const Node &t)const
{
return val==t.val?(pos<t.pos):(val<t.val);
}
}pre[N];
int main()
{
string s;
while(cin>>s)
{
int ans=0;
pre[0].val=pre[0].pos=0;
int n=s.length();
for(int i=1;i<=n;i++)
{
pre[i].val=pre[i-1].val+(s[i-1]=='0'?-1:1);//如果是0,我们用-1表示
pre[i].pos=i;
if(!pre[i].val) //如果pre[i].val==0说明[1,i]这个子串0、1个数一样多
ans=max(ans,pre[i].pos);
}
sort(pre+1,pre+n+1);//排序
//求中间某个区间s[l...r]满足要求,且长度更长
for(int i=1;i<=n;i++)//枚举子串的开始位置
{
int j=i+1;//子串的开始位置为pre[i].pos+1,结束位置为pre[j-1].pos
while(j<=n&&pre[j].val==pre[i].val)
j++;
ans=max(ans,pre[j-1].pos-pre[i].pos);
}
cout<<ans<<endl;
}
return 0;
}