Codeforces-873B:Balanced Substring(DP)
来源:互联网 发布:淘宝买家怎么买运费险 编辑:程序博客网 时间:2024/04/23 19:24
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.
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.
If there is no non-empty balanced substring in s, print 0. Otherwise, print the length of the longest balanced substring.
811010111
4
3111
0
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.
思路:num[i][2]分别记录[0,i]中0的个数和1的个数。那么在第i个字符处,若存在k<i使得num[k][0]-num[k][1]==num[i][0]-num[i][1],那么[k+1,i]这一段为balanced substring。
#include<bits/stdc++.h>using namespace std;const int MAX=2e5;int n,num[MAX][2],ans=0;int one[MAX],zero[MAX];char s[MAX];int main(){ memset(num,0,sizeof num); memset(one,1e9+7,sizeof one); memset(zero,1e9+7,sizeof zero); scanf("%d%s",&n,s+1); for(int i=1;i<=n;i++) { num[i][1]=num[i-1][1]; num[i][0]=num[i-1][0]; num[i][s[i]-'0']++; if(num[i][0]>num[i][1])zero[num[i][0]-num[i][1]]=min(zero[num[i][0]-num[i][1]],i); if(num[i][1]>num[i][0])one[num[i][1]-num[i][0]]=min(one[num[i][1]-num[i][0]],i); } for(int i=1;i<=n;i++) { if(num[i][0]==num[i][1])ans=max(ans,i); else { if(num[i][0]>num[i][1])ans=max(ans,i-zero[num[i][0]-num[i][1]]); if(num[i][1]>num[i][0])ans=max(ans,i-one[num[i][1]-num[i][0]]); } } cout<<ans<<endl; return 0;}
- Codeforces-873B:Balanced Substring(DP)
- Codeforces 873 B. Balanced Substring
- (Codeforces 873B)B. Balanced Substring [前缀和]+思维
- 【Codeforces B. Balanced Substring】
- Codeforces B. Balanced Substring
- CodeForces 873B Balanced Substring(前缀和+思维)
- CF B Balanced Substring(DP思想)
- codeforces 837B Balanced Substring
- Balanced Substring 873B
- codeforces——873B —— Balanced Substring
- Codeforces 873B Balanced Substring(利用前缀和找和为0的子串)
- Educational Codeforces Round 30 B.Balanced Substring
- Educational Codeforces Round 30 B. Balanced Substring
- Educational Codeforces Round 30 B. Balanced Substring
- Educational Codeforces Round 30-B-Balanced Substring
- CodeFroces 873B. Balanced Substring(思维题)
- CF 873 B. Balanced Substring【map】
- codeforces Balanced Substring
- L2-013. 红色警报
- 百钱买百鸡
- 构造函数与 new 命令
- C语言中的二级指针和二维数组问题
- Java代码获取oracle存储过程返回值
- Codeforces-873B:Balanced Substring(DP)
- nutch solr系列之(三)solr 4.8.1 支持中文分词
- c#实验解答(9)
- iOS APP内购功能实现研究资料
- 【1701H1】【穆晨】【171018】连续第八天总结
- c#实验解答(10)
- Qt开发====>五子棋游戏
- 萌新的看毛片(kmp)学习日记(下标从0开始)
- 为了c币