欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

题解 | Crazy Binary String-2019牛客暑期多校训练营第三场B题

程序员文章站 2022-04-01 15:33:56
...

题目来源于牛客竞赛:https://ac.nowcoder.com/acm/contest/discuss
题目描述:
ZYB loves binary strings (strings that only contains ‘0’ ‘1’ ). And he loves equal binary strings more, where the number of ‘0’ and the number `1’ in the string are equal.

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

A string v is a substring of a string w if v is empty, or there are two integers l and r(1≤l≤r≤|w|) such that v=w1wl+1…wr.A string v is a subsequence of a string \ w w if it can be derived from w 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 N (1≤N≤100000), the length of the original string T. The second line contains a binary string with exactly N characters, the original string T.

输出描述:
Print two integers A and B, denoting the answer for substring and subsequence respectively.

示例1:
输入
8
01001001

输出
4 6

题解:
子序列显然能取满,就是min(1的个数,0的个数)
子串的话,需要稍微统计一下
如果字符是’1’值设为1,否则设为-1,求一遍前缀和。
一个子串(l,r)满足要求,即S[r]-S[l-1]=0
直接扫过去,一遍记录是[l-1]的情况,一边每次询问是否有=S[r]的存在
时间复杂度:O(N)

代码:

#include<bits/stdc++.h>
#define N 100005
using namespace std;
map<int,int>G;
int a[N],n;char s[N];
int main(){
	//freopen("test7.in","r",stdin);
	scanf("%d",&n);
	scanf("%s",s+1);
	for (int i=1;i<=n;i++)
		a[i]=a[i-1]+((s[i]=='1')?1:-1);
		
	//a[r]-a[l-1]==0
	int ans=0;
	G[0]=0;
	for (int i=1;i<=n;i++)
		if (G.find(a[i])!=G.end())
			ans=max(ans,i-G[a[i]]);
		else
			G[a[i]]=i;
	
	int zero=0,one=0;
	for (int i=1;i<=n;i++)
		if (s[i]=='0') zero++;else one++;
	printf("%d %d\n",ans,min(zero,one)*2);
}

更多问题,更详细题解可关注牛客竞赛区,一个刷题、比赛、分享的社区。
传送门:https://ac.nowcoder.com/acm/contest/discuss