Codeforces B. Balanced Substring __Codeforces

來源:互聯網
上載者:User

B. Balanced Substring
time limit per test1 second
memory limit per test256 megabytes
inputstandard input
outputstandard output
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.

Examples
input
8
11010111
output
4
input
3
111
output
0
Note
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.

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

題意 : 字串中有多少 0 和 1 數量相同的子串

思路 : 把 0 替換成 -1,求出首碼和,並記錄下該首碼和的位置,在遇到相同的首碼和時更新最大長度即可

AC代碼:

#include<bits/stdc++.h>using namespace std;const int MAX = 1e5 + 10;int n,a[MAX];map <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;}
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.