您的位置:首页 > 其它

Educational Codeforces Round 30 Balanced Substring 前缀和

2017-10-13 00:36 381 查看
我是傻逼啊

没想一下,直接按 二分做的

其实就是 0 1 记录前缀和问题

我代码中的 mp 作用就是 映射 i 位置 和 前 i 个元素的和,,,

当有两个前缀和想同时,说明他们之间的和是0,也就是我们要找的长度

----------------------------------------------------

更新一下,这个 “ 他们之间的和是0 ” ,意思是 0 1 数量相同,我们记录的 x y 的差值是零,

对于每一个差值,我们记录最小的那个 下标 这样最后我们找到 相同差值的时候,一定值最长的区间

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <string>
#include <cmath>
#include <set>
#include <map>
#include <stack>
#include <queue>
#include <ctype.h>
#include <vector>
#include <algorithm>
#include <sstream>
#define PI acos(-1.0)
#define in freopen("in.txt", "r", stdin)
#define out freopen("out.txt", "w", stdout)
using namespace std;
typedef long long ll;
const int maxn = 100000 + 7, INF = 0x3f3f3f3f, mod = 1e9 + 7;

int n, x = 0, y = 0;
char s[maxn];

map<int,int> mp;

int main() {
scanf("%d%s", &n, s+1);
int ans = 0;
mp[0] = 0;
for(int i = 1; i <= n; ++i) {
if(s[i] == '1') {
x++;
}
else y++;
if(mp.count(y-x)) {
ans = max(ans, i-mp[y-x]);
}
else {
mp[y-x] = i;
}
}

printf("%d", ans);

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: