列表

详情


NC51460. Crazy Binary String

描述

ZYB loves binary strings (strings that only contains `0' and `1'). And he loves more, where the number of `0' and the number of `1' in the string are equal.

ZYB wants to choose a substring from an original string  so that it is an with the longest length possible. He also wants to choose a subsequence of which meets the same requirements.

A string is a substring of a string if is empty, or there are two integers and  such that . A string is a subsequence of a string   if it can be derived from   by deleting any number (including zero) of characters without changing the order of the remaining characters. 

For simplicity, you only need to output the maximum possible length. Note that the empty string is both a substring and a subsequence of any string.

输入描述

The first line of the input contains a single integer , the length of the original string . The second line contains a binary string with exactly  characters, the original string .

输出描述

Print two integers  and , denoting the answer for substring and subsequence respectively.

示例1

输入:

8
01001001

输出:

4 6

原站题解

上次编辑到这里,代码来自缓存 点击恢复默认模板

C++14(g++5.4) 解法, 执行用时: 43ms, 内存消耗: 5088K, 提交时间: 2019-07-25 12:27:04

#include<bits/stdc++.h>
using namespace std;
char a[100010];
map<int,int> mp;
int main(){
    int n;scanf("%d",&n);
    scanf("%s",a+1);
    int num=0,ans=0;
    for (int i=1;i<=n;i++){
        if (a[i]=='1') num++;
        if (mp[i-2*num]||i==2*num) ans=max(ans,i-mp[i-2*num]);
        else mp[i-2*num]=i;
    }
    printf("%d %d\n",ans,2*min(n-num,num));
    return 0;
}

Python3 解法, 执行用时: 115ms, 内存消耗: 18020K, 提交时间: 2022-10-01 12:51:55

n = int(input())

s = input()

anb = 2 * min(s.count('0'), s.count('1'))

dic = {}
s = '0' + s
ana = 0
idx = 0
for i in range(n+1):
    if s[i] == '0':
        idx -= 1
    else:
        idx += 1
    tmp = dic.get(idx, -1)
#     print(idx, tmp)
    if tmp != -1:
        ana = max(ana, i - tmp)
    else:
        dic[idx] = i
        
print(ana, anb)

C++(clang++ 11.0.1) 解法, 执行用时: 4ms, 内存消耗: 908K, 提交时间: 2022-12-06 12:18:33

#include<bits/stdc++.h>
using namespace std;
const int m=1e5;
int a[m<<1],n,c,ans;
char s[m+5];
int main(){
	scanf("%d%s",&n,s+1);
	for(int i=1;i<=n;i++)
	{
		c+=s[i]=='1'?1:-1;
		if(!a[m+c]&&c)
		a[m+c]=i;
		else
		ans=max(ans,i-a[m+c]);
	}
	printf("%d %d\n",ans,n-abs(c));
}

上一题