题解 CF1430D 【String Deletion】
这题比C简单多了
每次操作包含两步:删除任意一个字符,删除最前面的连续字段。
考虑最简单的情况,即
而如果
代码如下:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<algorithm>
#define ll long long
#define fo(i,x,y) for(register int i=x;i<=y;++i)
#define go(i,x,y) for(register int i=x;i>=y;--i)
using namespace std;
inline int read(){
int x=0,fh=1;
char ch=getchar();
while(!isdigit(ch)){
if(ch=='-') fh=-1;
ch=getchar();
}
while(isdigit(ch)){
x=(x<<1)+(x<<3)+ch-'0';
ch=getchar();
}
return x*fh;
}
const int maxn=2e5+5;
string s;
int a[maxn],top;
void work(){
int n=read(),last=0,ans;
top=0;
cin>>s;
fo(i,1,n-1){
if(s[i]!=s[i-1]) a[++top]=i-last,last=i;//记录连续字段的长度
}
a[++top]=n-last;
int pos=1;//pos用来记录上一次操作中长度大于1的连续字段的下标
fo(i,1,top){
while(pos<=top&&a[pos]==1) pos++;
//printf("%d ",pos);
a[pos]--;
if(pos>top){
ans=i-1+(top-i+2)/2;
printf("%d\n",ans);
return;
}
if(pos<=i) pos=i+1;
}
printf("%d\n",top);
//puts("");
}
int main(){
int T=read();
while(T--){
work();
}
return 0;
}