【2019牛客暑期多校训练营(第三场)- B】Crazy Binary String(思维,01串,前缀和)
題干:
鏈接:https://ac.nowcoder.com/acm/contest/883/B
來源:牛客網
?
ZYB loves binary strings (strings that only contains `0' and `1'). And he loves equal?binary?strings\textit{equal binary strings}equal?binary?strings 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 ?T\ T?T?so that it is an equal?binary?string\textit{equal binary string}equal?binary?string with the longest length possible. He also wants to choose a subsequence of ?T\ T?T which meets the same requirements.
A string ?v\ v?v is a substring of a string ?w\ w?w if ?v\ v?v is empty, or there are two integers ?l\ l?l and r?(1≤l≤r≤∣w∣)r \ (1 \le l \le r \le |w|)r?(1≤l≤r≤∣w∣)?such that v=wlwl+1?wrv=w_lw_{l+1}\cdots w_rv=wl?wl+1??wr?. A string ?v\ v?v is a subsequence of a string ?w\ w?w? if it can be derived from ?w\ w?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)N \ (1 \le N \leq 100000)N?(1≤N≤100000), the length of the original string ?T\ T?T. The second line contains a binary string with exactly ?N\ N?N?characters, the original string ?T\ T?T.輸出描述:
Print two integers ?A\ A?A and ?B\ B?B, denoting the answer for substring and subsequence respectively.示例1
輸入
復制
8 01001001輸出
復制
4 6題目大意:
給你一個01字符串,讓你求01個數相等的子串和子序列長度。
解題報告:
? ?對于子序列肯定好說,直接就是0和1取個最大值再乘以2就是答案。
? ?對于子串,正常想法是對于偶數長度進行二分,但是其實是沒有單調性的,比如這個樣例:00111100,長度為6是不成立的,長度為8是成立的。所以正解是用前綴和,記錄第一個出現的位置即可。注意初始化0的初始位置是0。因為他可以從頭開始取。注意取長度的時候不需要再+1了。
AC代碼:
#include<cstdio> #include<iostream> #include<algorithm> #include<queue> #include<map> #include<vector> #include<set> #include<string> #include<cmath> #include<cstring> #define FF first #define SS second #define ll long long #define pb push_back #define pm make_pair using namespace std; typedef pair<int,int> PII; const int MAX = 2e5 + 5; const int ZERO = 1e5; int sum[MAX]; int pos[MAX]; int num[2],n; char s[MAX]; int main() {memset(pos,-1,sizeof pos);cin>>n;scanf("%s",s+1);for(int i = 1; i<=n; i++) s[i] -= '0',num[s[i]]++,sum[i] = sum[i-1] + (s[i] == 0 ? -1 : 1);int ans2 = min(num[0],num[1])*2;int ans1 = 0;pos[ZERO] = 0;for(int i = 1; i<=n; i++) {if(pos[ZERO+sum[i]] != -1) ans1 = max(ans1,i - pos[ZERO + sum[i]]);else pos[ZERO+sum[i]] = i;}printf("%d %d\n",ans1,ans2);return 0 ; }?
總結
以上是生活随笔為你收集整理的【2019牛客暑期多校训练营(第三场)- B】Crazy Binary String(思维,01串,前缀和)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 《饥荒》哈姆雷特控制台代码一览
- 下一篇: 《饥荒》水中木版本新增控制台代码一览