NC51460. Crazy Binary 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)); }