zoukankan      html  css  js  c++  java
  • 1393 0和1相等串

    基准时间限制:1 秒 空间限制:131072 KB 
    给定一个0-1串,请找到一个尽可能长的子串,其中包含的0与1的个数相等。
    Input
    一个字符串,只包含01,长度不超过1000000。
    Output
    一行一个整数,最长的0与1的个数相等的子串的长度。
    Input示例
    1011
    Output示例
    2
    思路:把0变成-1,然后01相等,那个段的和就是0,然后维护前缀和,当前缀和为0的时候,我们更新最长的,那么当当前前缀不是0的时候,如果我们知道最前面的和
    等于当前值的时候(j),那么[j+1,i]的和就为0,那么当前值和最大比较更新。复杂n*log(n);
     1 #include<stdio.h>
     2 #include<algorithm>
     3 #include<iostream>
     4 #include<string.h>
     5 #include<queue>
     6 #include<math.h>
     7 #include<set>
     8 #include<vector>
     9 #include<string.h>
    10 #include<map>
    11 using namespace std;
    12 typedef long long LL;
    13 int sum[1000005];
    14 map<int,int>my;
    15 char str[1000005];
    16 int ans[1000005];
    17 int main(void)
    18 {
    19     my.clear();int i , j;
    20     scanf("%s",str);
    21     int l= strlen(str);
    22     for(i = 0;i < l; i++)
    23     {
    24         if(str[i] == '0')
    25         {
    26             ans[i+1] = -1;
    27         }
    28         else ans[i+1] = 1;
    29     }
    30     my[0] = 0;int maxx = 0;
    31     sum[0] = 0;
    32     for(i = 1; i <= l; i++)
    33     {
    34         sum[i] = sum[i-1] + ans[i];
    35         if(sum[i] == 0)
    36         {
    37             maxx = max(i,maxx);
    38         }
    39         else
    40         {
    41             if(my[sum[i]]==0)
    42             {
    43                 my[sum[i]] = i;
    44             }
    45             else maxx = max(i-my[sum[i]],maxx);
    46         }
    47     }
    48     printf("%d
    ",maxx);
    49     return 0;
    50 }
    
    
    油!油!you@
  • 相关阅读:
    TCP/IP,Http,Socket,XMPP的区别
    CygWin 常用命令
    js打印数组,js打印对象的方法
    中奖概率算法(php 可用于刮刮卡,大转盘等抽奖算法)
    sql语句优化
    求职简历怎么写,看看百度吐槽
    c#学习笔记之WPF Application和Windows Form Applications
    c#学习笔记之XML
    c#学习笔记之LINQ
    c#学习笔记之字符串和正则表达式
  • 原文地址:https://www.cnblogs.com/zzuli2sjy/p/5843749.html
Copyright © 2011-2022 走看看