取硬币(思维)

取硬币(思维)

Description

n个硬币排成一排,你可以取走其中连续的一段硬币,但必须要求这段硬币中正面朝上的个数等于反面朝上的个数,那么你最多可以取走多少枚硬币?

Input

多组实例测试,每组输入一个01字符串(长度小于1000000),其中0表示反面朝上,1表示正面朝上

Output

对于每组数据,输出能取走的最多硬币数量

Sample Input

10110

Sample Output

Case #1: 4

 

令t为当前1的个数与0的个数的差,那么遍历字符串,只要这个差值之前出现过,就说明中间这一段0和1的个数一定相等

 

#include <bits/stdc++.h>
const int INF=0x3f3f3f3f;
typedef long long LL;
const double eps =1e-8;
const int mod=1e9+7;
const int maxn=1e5+10;
using namespace std;

char str[1000005];
map<int,int> mp;

int main()
{
    #ifdef DEBUG
    freopen("sample.txt","r",stdin);
    #endif
    
    int cnt=0;
    while(~scanf("%s",str+1))
    {
        mp.clear();
        cnt++;
        int ans=0;
        int num1=0,num2=0;
        mp[0]=0;
        for(int i=1;str[i];i++)
        {
            if(str[i]=='1') num1++;
            else num2++;
            if(mp.count(num1-num2))
            {
                ans=max(ans,i-mp[num1-num2]);
            }
            else mp[num1-num2]=i;
        }
        printf("Case #%d: %d\n",cnt,ans);
    }
    
    return 0;
}

 

 

-

posted @ 2020-03-12 01:26  jiamian22  阅读(197)  评论(0编辑  收藏  举报