51Nod 1393 0和1相等串
来源:互联网 发布:mac中照片的存储位置 编辑:程序博客网 时间:2024/06/06 02:54
1393 0和1相等串
基准时间限制: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;}
0 0
- 51nod 0和1相等串
- 51nod 1393 0和1相等串(前缀和)
- 51NOD 1393 0和1相等串
- 51nod 1393:0和1相等串
- 51nod 1393 0和1相等串 (连续区间)
- 51nod 1393 0和1相等串
- 51Nod-1393-0和1相等串
- 51nod 1393 0和1相等的串
- 51nod oj 1393 0和1相等串 【贪心】
- 51Nod 1393 0和1相等串
- 51nod 1393 0和1相等串(鸽巢)
- 51nod 1393 0和1相等串
- 51nod-【1393 0和1相等串】
- 51nod 1393 0和1相等串【思维】
- 51Nod 1393 0和1相等串
- 51nod 1393 0和1相等串
- 51nod 1393 0和1相等串 思路
- 51nod 1393 0和1相等串
- Intent和PendingIntent
- hdu 1402 A * B Problem Plus[【FFT】
- MySQL基本概念
- linux常用命令和文件操作命令
- 单片机小项目总结
- 51Nod 1393 0和1相等串
- 方法重写与方法重载 静态
- Mysql 存储引擎中InnoDB与Myisam的主要区别
- Google Chrome v53.0.2785.89
- CodeBlocks配置VS2013编译器并运行OpenCV
- Spring @Component、@Repository、@Service、@Controller
- Bootstrap(1)基础概念
- BZOJ1072: [SCOI2007]排列perm 状压DP
- Oracle 创建表空间