Educational Codeforces Round 30 - B. Balanced Substring【思维+map】
2017-10-13 21:32
429 查看
B. Balanced Substring
time limit per test1 secondmemory limit per test256 megabytes
inputstandard input
outputstandard output.
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.Examples
input
811010111
output
4input
3111
output
0Note
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.
题意:给你一个n和一个长度为n的字符串(只包含01),问你求一个最长的区间使得区间里0的个数等于1的个数
分析: 因为看到连续这个关键字,一直往Two Pointers 这边想,结果就GG了,一早看见解题发现好坑呀,直接利用map的“BUG”轻松过:首先定义‘0’的话就记做-1,‘1’还是记做1,先用一个r变量来记录前缀和,只要“前缀和”没出现过,记录下坐标,只要出现过,更新下答案,这个思想就像是一个二次函数,到达同一个y值,因为该y值到顶的高度一定一样,所以其区间和比为零,这样应该形象点吧,在不懂的,直接手算模拟下就OK啦
参考代码
#include<bits/stdc++.h> using namespace std; string s; int n; map<int,int> m; int main() { ios_base::sync_with_stdio(0); cin>>n>>s; m[0] = -1; int ans = 0,r = 0; for(int i = 0; i < n; i++) { r += s[i] == '1'?1:-1; if(m.count(r)) ans = max(ans,i-m[r]); else m[r] = i; } cout<<ans<<endl; return 0; }
如有错误或遗漏,请私聊下UP,thx
相关文章推荐
- Educational Codeforces Round 30 - Strange Game On Matrix 前缀和 问题
- Educational Codeforces Round 30 D.Merge Sort
- Educational Codeforces Round 7(E)贪心,思维
- Educational Codeforces Round 30 总结
- Educational Codeforces Round 30 D.Merge Sort
- Educational Codeforces Round 11(A)思维,数学
- Educational Codeforces Round 30 Balanced Substring 前缀和
- Educational Codeforces Round 30 D.Merge Sort
- Educational Codeforces Round 30(A+B)
- Educational Codeforces Round 30 A. Chore
- Educational Codeforces Round 30 D.Merge Sort
- Educational Codeforces Round 2 E. Lomsat gelral 启发式合并map
- Educational Codeforces Round 28 Four Segments 前缀和 + 思维
- Educational Codeforces Round 30 B.Balanced Substring
- Educational Codeforces Round 30 D.Merge Sort
- Educational Codeforces Round 30 D.Merge Sort
- Educational Codeforces Round 37 C. Swap Adjacent Elements 思维
- Educational Codeforces Round 5 E. Sum of Remainders (思维题)
- Educational Codeforces Round 30-归并排序计数&构造- Merge Sort
- Educational Codeforces Round 30 题解