这题比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;
}