思路
我们考虑保留一段区间 的所有 ,那么需要操作的次数就是 和 中的 的个数加上 中的 的个数。
求个前缀和,令 表示 中的 的个数, 的答案就是:
考虑枚举每一个 ,由于我们要让答案最小, 就取 中使得 最小的那个( 表示删掉所有 ),其实就是 的前缀最小值。直接算即可,时间复杂度 。
笑点解析:这是我前六道题里花时间最长的一道。
代码
#include<bits/stdc++.h>
#define gc getchar
#ifndef DEBUG
#define debug
#endif
using namespace std;
template<typename T>void read(T &x){x = 0;int f = 1;char c = gc();while(!isdigit(c)){if(c == '-') f = -1;c = gc();}while(isdigit(c)) x = x * 10 + c - '0',c = gc();x *= f;}
const int N = 300000;
int T,n,p[N],r,l,ans,x[N];
char s[N];
int main(){
read(T);
while(T --){
ans = 2e9;
read(n);scanf("%s",s + 1);
for(int i = 1;i <= n;i ++) p[i] = p[i - 1] + s[i] - '0';//前缀和
for(int i = 0;i <= n;i ++) x[i] = 2 * p[i] - i;//取 l-1=x 时对答案造成的影响
for(int i = 1;i <= n;i ++) x[i] = min(x[i],x[i - 1]);//取 x 的前缀最小值
for(int i = 1;i <= n;i ++) ans = min(ans,p[n] + (i - 2 * p[i]) + x[i]);
printf("%d\n",ans);
}
return 0;
}