基准时间限制:1 秒 空间限制:131072 KB 分值: 20
难度:3级算法题
给定一个0-1串,请找到一个尽可能长的子串,其中包含的0与1的个数相等。
Input
一个字符串,只包含01,长度不超过1000000。
Output
一行一个整数,最长的0与1的个数相等的子串的长度。
Input示例
1011
Output示例
2
思路:先扫描一遍字符串记录1和0相差的次数,然后按次数大小排序(为的是让相差次数相同的在一起),再按0出现的次数排序,然后用相差数相同的0(或1)的最大次数减去最小次数,在这里面找最大值,就是结果。
理由:不妨设d(i) = (mi, ni, ci) (s[0,...i] 0,1出现的次数,次数的差值),若s[i...j]中0,1出现次数相同,那么mj - mi = nj - ni => mi - ni = mj - nj即
s[0..i] 和s[0...j] 0,1出现次数的差值相同(ci = cj)这样只需记录次数的差值还有0(或1)的次数就行了#include<cstdio> #include<cstring> #include<algorithm> const int maxn = 1e6 + 10; using namespace std; typedef pair<int, int> P; P p[maxn]; char s[maxn]; int solve(int l) { sort(p, p + l); int ind = 0, ans = 0; while(ind < l) { int i; for(i = ind + 1; i < l && p[i].first == p[ind].first; i++); ans = max(ans, p[i - 1].second - p[ind].second); ind = i; } return ans * 2; } int main() { while(scanf("%s", s) != EOF) { int l = strlen(s); int a = 0, b = 0; for(int i = 0; i < l; i++) { if(s[i] == '0') a++; else b++; p[i].first = b - a; p[i].second = a; } p[l].first = p[l].second = 0; l++; printf("%d\n", solve(l)); } return 0; }