Codeforces B. Balanced Substring __codeforces

Source: Internet
Author: User

B. Balanced Substring
Time limit per test1 second
Memory limit per test256 megabytes
Inputstandard input
Outputstandard output
You are 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 are have to determine the length of the longest balanced substring of s.

Input
The 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.

Examples
Input
8
11010111
Output
4
Input
3
111
Output
0
Note
In the "the" example you can choose the substring [3, 6]. It is balanced, and its length is 4. Choosing the substring [2, 5] is also possible.

In the second example it's impossible to find a non-empty balanced substring.

How many substrings in the string have the same number of 0 and 1

Idea: replace 0 with 1, find the prefix and, record the prefix and the position, and update the maximum length when the same prefix is encountered.

AC Code:

 #include <bits/stdc++.h> using namespace std; const int MAX = 1e5 + int N,a[max]; Map &L
T;int,int> m;
Char S[max];
    int main () {int n;
    scanf ("%d%s", &n,s + 1);
        for (int i = 1; I <= n; i++) if (s[i] = = ' 0 ') a[i] =-1;
    else a[i] = 1;
    int ans = 0,sum = 0;
    M[0] = 1;
        for (int i = 1; I <= n; i++) {ans = a[i];
        if (M[ans]) sum = max (Sum,i-m[ans] + 1);
    else M[ans] = i + 1;
    printf ("%d\n", sum);
return 0; }

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.