跳到正文

题解

题解 CF1430D 【String Deletion】

vectorwyx约 3 分钟
原文
文章信息与版本

文章信息

发布
2020年10月12日
收录
2026年3月2日
更新
2026年11月9日
篇幅
约 3 分钟
题目
CF1430D

版本

  1. v2当前
  2. v1

这题比C简单多了


每次操作包含两步:删除任意一个字符,删除最前面的连续字段。

考虑最简单的情况,即 s=010101……s=010101…… 或 s=101010……s=101010……,设 ss 的长度为 lenlen,显然答案为 ⌈len2⌉\lceil\frac{len}{2}\rceil。

而如果 0/10/1 在某些地方连续出现了多次,我们在删去这些连续的字段之前贪心地把删除单个字符的操作放在这些字段里肯定是最优的。由于我们只关心连续字段的长度,因此可以开一个数组记录每个字段的长度,对于每次操作,先删掉任意一个还未被删去的连续字段中的一个字符,再删去最前面的连续字段。前者具有单调性,维护一下就可做到 O(n)O(n) 的复杂度。

代码如下:

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;
}
原文
存档评论3 条抓取于