zoukankan      html  css  js  c++  java
  • [Codeforces 873B]Balanced Substring

    Description

    You are given a string s consisting only of characters 0 and 1. A substring [l, r] of s is a string slsl + 1sl + 2... sr, and its length equals to r - l + 1. A substring is called balanced if the number of zeroes (0) equals to the number of ones in this substring.

    You have to determine the length of the longest balanced substring of s.

    Input

    The first line contains n (1 ≤ n ≤ 100000) — the number of characters in s.

    The second line contains a string s consisting of exactly n characters. Only characters 0 and 1 can appear in s.

    Output

    If there is no non-empty balanced substring in s, print 0. Otherwise, print the length of the longest balanced substring.

    Sample Input

    8
    11010111

    Sample Output

    4

    Hint

    In the first example you can choose the substring [3, 6]. It is balanced, and its length is 4. Choosing the substring [2, 5] is also possible.

    题解

    令所有$0$为$-1$,做一遍前缀和,若$L$,$R$前缀和相同,则$[L+1,R]$是一段可行区间。

     1 //It is made by Awson on 2017.10.15
     2 #include <set>
     3 #include <map>
     4 #include <cmath>
     5 #include <ctime>
     6 #include <cmath>
     7 #include <stack>
     8 #include <queue>
     9 #include <vector>
    10 #include <string>
    11 #include <cstdio>
    12 #include <cstdlib>
    13 #include <cstring>
    14 #include <iostream>
    15 #include <algorithm>
    16 #define LL long long
    17 #define Min(a, b) ((a) < (b) ? (a) : (b))
    18 #define Max(a, b) ((a) > (b) ? (a) : (b))
    19 #define sqr(x) ((x)*(x))
    20 using namespace std;
    21 const int N = 100000;
    22 const int INF = ~0u>>1;
    23 void read(int &x) {
    24     char ch; bool flag = 0;
    25     for (ch = getchar(); !isdigit(ch) && ((flag |= (ch == '-')) || 1); ch = getchar());
    26     for (x = 0; isdigit(ch); x = (x<<1)+(x<<3)+ch-48, ch = getchar());
    27     x *= 1-2*flag;
    28 }
    29 
    30 int n, a, zero[N+5], one[N+5];
    31 int sum, ans;
    32 char ch[N+5];
    33 
    34 void work() {
    35     read(n); scanf("%s", ch+1);
    36     for (int i = 1; i <= n; i++) {
    37         a = ch[i]-48;
    38         if (a == 1) sum++;
    39         else sum--;
    40         if (sum > 0) {
    41             if (one[sum]) ans = Max(ans, i-one[sum]);
    42             else one[sum] = i;
    43         }else if (sum < 0) {
    44             if (zero[sum]) ans = Max(ans, i-zero[sum]);
    45             else zero[sum] = i;
    46         }
    47         else ans = i;
    48     }
    49     printf("%d
    ", ans);
    50 }
    51 int main() {
    52     work();
    53     return 0;
    54 }
  • 相关阅读:
    android启动模式2
    acvitity的日常 启动模式(上)
    Fragment 切换问题
    异常处理
    Xutils的使用 转载 带自己细细研究
    hibernate 增删改
    OGNL
    JDBC
    Struts 文件的上传与下载
    ActionContext和ServletActionContext小结
  • 原文地址:https://www.cnblogs.com/NaVi-Awson/p/7673779.html
Copyright © 2011-2022 走看看