51nod1393 01串相等 思维
来源:互联网 发布:java二维数组 编辑:程序博客网 时间:2024/06/08 10:00
题目:
给定一个0-1串,请找到一个尽可能长的子串,其中包含的0与1的个数相等。
Input
一个字符串,只包含01,长度不超过1000000。
Output
一行一个整数,最长的0与1的个数相等的子串的长度。
Input示例
1011
Output示例
2
思路:dp[i][0]记录前i个字符中0的个数,dp[i][1]记录前i个字符中1的个数。如果对于不同的i有dp[i][0] - dp[i][1]相等,则两个i间必然是0的个数等于1.记录每个差值,找到最大即可。ps:若差值为0,他的最左边是空串开始的。。
#include <iostream>#include <cstdio>#include <string>#include <cstring>#include <fstream>#include <algorithm>#include <cmath>#include <queue>#include <stack>#include <vector>#include <map>#include <set>#include <iomanip>using namespace std;#define maxn 1000005#define MOD 1000000007#define mem(a , b) memset(a , b , sizeof(a))#define LL long long#define INF 1000000000char a[maxn];string str;int dp[maxn][2];struct node{ int val; int id;}ans[maxn];bool cmp(node n1 ,node n2){ if(n1.val == n2.val) return n1.id < n2.id; else return n1.val < n2.val;}int main(){ while(scanf("%s" , a) != EOF) { str = a; int len = str.size(); mem(dp , 0); int pos0 = 1 , pos1 = 1 ; for(int i = 1 ; i <= len ; i ++) { if(str[i-1] == '0') {dp[i][0] += (dp[i-1][0] + 1); dp[i][1] = dp[i-1][1];} else if(str[i-1] == '1') {dp[i][1] += (dp[i-1][1] + 1); dp[i][0] = dp[i-1][0];} ans[i].val = (dp[i][1] - dp[i][0]); ans[i].id = i; } /* if(dp[len][0] == dp[len][1]) { printf("%d\n" , len); continue; }*/ ans[0].val=0,ans[0].id=0; sort(ans , ans + len + 1 , cmp); int maxx = 0 , st = 0; for(int i = 1 ; i <= len ; i ++ ) { if(ans[i].val != ans[st].val) { maxx = max(maxx , ans[i-1].id - ans[st].id); st = i; } } printf("%d\n" , maxx); } return 0;}
0 0
- 51nod1393 01串相等 思维
- 51nod1393 0和1相等串 思维题
- 51nod1393
- 51nod 1393 0和1相等串【思维】
- 51nod 1393 0和1相等串 (思维+前缀和)
- 51nod 0和1相等串
- 01相等的字串。
- 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相等串】
- Color Me Less
- Codeforces 617 C. Watering Flowers
- Json数据手动解析
- unable to start activity componentinfo java lang nullpointerexception
- struts2拦截器的实现原理及源码剖析
- 51nod1393 01串相等 思维
- android基本架构
- Android开发基础之Adapter
- 大道至简,悟在天成
- Android面试——Activity的四种启动模式
- SVN服务端 Subversion安装与配置 注意的细节问题
- java锁(1)之ReentrantLock
- eclipse环境搭建之四:Go。但没有成功,后转为LiteIDE。
- 40. Combination Sum II leetcode Python 2016 new season