Educational Codeforces Round 30
来源:互联网 发布:知乎回答如何取消匿名 编辑:程序博客网 时间:2024/05/23 00:03
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.
题意:
求最长子串的长度,这个子串中0,1的数量相等。
POINT:
记录0,1,遇1值+1,遇0值-1。记录每一个出现的数的第一次的位置,当他再次出现,则第一次和再次出现的位置中就是0,1次数相等的子串。判断长度。
特殊的,值为0时,就直接把当前位置和ans比较,因为这是便利到的位置和之前的所有0,1都抵消了。
0 1 0 1 0 0 0 1 1 1 1 1
0 -1 0 -1 0 -1 -2 -3 -2 -1 0 1 2
如上图。
这题要反思,临睡前才想出来。
#include <stdio.h>#include <algorithm>#include <string.h>#include <iostream>#include <math.h>#include <map>using namespace std;const int maxn =100044;char s[maxn];int a[maxn];map<int,int>fir;map<int,int>last;int main(){ int n; cin>>n; scanf("%s",s+1); a[0]=0; int ans=0; for(int i=1;i<=n;i++){ if(s[i]=='0') a[i]=a[i-1]-1; else a[i]=a[i-1]+1; if(fir[a[i]]==0){ fir[a[i]]=i; } last[a[i]]=i; if(a[i]!=0) ans=max(last[a[i]]-fir[a[i]],ans); else ans=max(last[a[i]],ans); } printf("%d\n",ans); return 0;}
- Educational Codeforces Round 30
- Educational Codeforces Round 30
- Educational Codeforces Round 30
- Educational Codeforces Round 30
- Educational Codeforces Round 30 总结
- Educational Codeforces Round 30 题解
- Educational Codeforces Round 30 B C
- Educational Codeforces Round 30 A. Chore
- Educational Codeforces Round 30 B.Balanced Substring
- Educational Codeforces Round 30 D. Merge Sort
- Educational Codeforces Round 30 B. Balanced Substring
- Educational Codeforces Round 30 D.Merge Sort
- Educational Codeforces Round 30 Balanced Substring
- Educational Codeforces Round 30 B. Balanced Substring
- Educational Codeforces Round 30(A+B)
- Educational Codeforces Round 30-B-Balanced Substring
- Educational Codeforces Round 30 837A. Chores
- Educational Codeforces Round 1
- Mybatis入门基础
- Android Bitmap加载内存占用彻底分析
- javaUI之卡片布局管理器
- Browser对象
- Windows 10 和 Ubuntu 双系统安装(U盘启动)
- Educational Codeforces Round 30
- git修改远程仓库地址
- vCenter初始化数据中心和集群
- Python学习之路---Python 循环语句
- 微信小程序框架wxss(一)wxss概述
- 1 记滴滴实习面试记录
- 沉浸式状态栏 设置状态栏颜色
- BZOJ 2427: [HAOI2010]软件安装 Tarjan缩点 + DP
- bzoj3529 [Sdoi2014]数表(莫比乌斯反演+树状数组)