51nod-【1393 0和1相等串】
来源:互联网 发布:淘宝黑莓手机是真的吗 编辑:程序博客网 时间:2024/06/05 18:08
1393 0和1相等串
基准时间限制:1 秒 空间限制:131072 KB 分值: 20 难度:3级算法题
收藏
关注
给定一个0-1串,请找到一个尽可能长的子串,其中包含的0与1的个数相等。
Input
一个字符串,只包含01,长度不超过1000000。
Output
一行一个整数,最长的0与1的个数相等的子串的长度。
Input示例
1011
Output示例
2
网上有各种写法,其实题意让求出一个子串0,1个数相同,
我们可以把0看成-1,求出前缀和,记录每一个前缀和的位置
我们只需要把前缀和相同的相减求出最大值就行了
举个栗子: 1 2 4……44 55
看这个序列,如果2-44中间存在相加等于0的数那么前缀和相加等于1,
就会出现2次,我们只需要把位置相减就是其长度
#include<cstdio>#include<cstring>#include<algorithm>using namespace std;struct node{int sum;int pos;}a[1000000+11];char s[1000000+11];bool cmp(node d,node c){if(d.sum!=c.sum)return d.sum<c.sum;return d.pos<c.pos; } int main(){scanf("%s",s);int i,k,len=strlen(s);a[0].sum=0;a[0].pos=0;k=1;//对于a[0].pos,a[0].sum,一定要初始化开始没有把a[0].pos初始为0//对于011这样的字符我的输出为0,不懂为什么思考一下 for(i=0;i<len;++i){if(s[i]=='0'){a[k].sum=a[k-1].sum-1;a[k].pos=k; }else{a[k].sum=a[k-1].sum+1;a[k].pos=k; } ++k; }/*for(i=0;i<k;++i)printf("%d ",a[i].sum);printf("\n");*/ sort(a,a+k,cmp);/*for(i=0;i<k;++i)printf("%d %d\n",a[i].sum,a[i].pos);*/int dis,mmax=0;for(i=1;i<k-1;++i){if(a[i].sum==a[i+1].sum){int temp=a[i].pos;while(i<k-1&&a[i].sum==a[i+1].sum)++i;dis=a[i].pos-temp;if(dis>mmax) mmax=dis;} }printf("%d\n",mmax); 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相等串
- 对URL URI URN的思考
- 并发设计模式之Master-Worker模式
- Android EventBus源码解析 带你深入理解EventBus(转载)
- 关于pt、px、em的转换
- 3342 数据结构实验之二叉树三:统计叶子数
- 51nod-【1393 0和1相等串】
- phpstorm一些常见的快捷键
- Unity的常用快捷键
- Memcached 与 Redis 实现的对比(上)
- 解决Ajax请求跨域问题
- 如何使用sourcetree
- navicat for Mysql查询数据不能直接修改
- HTTP中Get和Post的区别
- view中path的使用