跳到正文

题解

题解 CF1303C 【Perfect Keyboard】

gyh20约 4 分钟
原文
文章信息与版本

文章信息

发布
2020年2月17日
收录
2026年6月14日
更新
2026年11月18日
篇幅
约 4 分钟
获赞
1
题目
CF1303C

版本

  1. v1当前

在最后的字母表中,每个字母至多和两个字母相邻。

记录下每个字母需要和那两个字母相邻(大于 22 直接判不可能)

之后做一个类似拓扑排序的东西

先把所有没有出现的字母存入答案。

注意:以下的相邻代表在给出的字符串中相邻并且没有在答案中出现过

1.1.找到一个只需要和一个字母相邻的字母,并存入答案。

2.2.加入这个相邻的字母,并找到与它相邻的字母。

3.3.如果存在两个相邻的字母,则输出 −1-1

4.4.如果还有没有使用的字母,重复步骤 11

C++
#include<cstdio>
#include<cstring>
#define re register
#define int long long
using namespace std;
inline int read(){
	re int t=0;
	re char v=getchar();
	while(v<'0')v=getchar();
	while(v>='0'){
		t=(t<<3)+(t<<1)+v-48;
		v=getchar();
	}
	return t;
}
int n,a[32],b[32];
char s[100002],ans[32];
bool v[32];
inline int find(){
	for(re int i=1;i<=26;++i)if(!v[i])if((!b[i]&&!v[i])||(v[a[i]]&&!v[i]))return i;
	return 27;
}
signed main(){
	v[0]=1;
	int t=read();
	while(t--){
		scanf("%s",s+1);
		n=strlen(s+1);
		bool ia=0;
		memset(a,0,sizeof(a));
		memset(b,0,sizeof(b));
		memset(v,0,sizeof(v));
		v[0]=1;
		for(re int i=1;i<n;++i){
			if(!a[s[i]-'a'+1]||a[s[i]-'a'+1]==s[i+1]-'a'+1){
				a[s[i]-'a'+1]=s[i+1]-'a'+1;
			}
			else if(!b[s[i]-'a'+1]||b[s[i]-'a'+1]==s[i+1]-'a'+1){
				b[s[i]-'a'+1]=s[i+1]-'a'+1;
			}
			
			else{
				ia=1;
				puts("NO");
				break;
			}
			if(!a[s[i+1]-'a'+1]||a[s[i+1]-'a'+1]==s[i]-'a'+1){
				a[s[i+1]-'a'+1]=s[i]-'a'+1;
			}
			else if(!b[s[i+1]-'a'+1]||b[s[i+1]-'a'+1]==s[i]-'a'+1){
				b[s[i+1]-'a'+1]=s[i]-'a'+1;
			}
			
			else{
				ia=1;
				puts("NO");
				break;
			}
		}
		if(ia)continue;
		int k,tot=0;
		while((k=find())<27){
			while(1){
				v[k]=1;
				ans[++tot]=k;
				if(v[a[k]]&&v[b[k]])break;
				if(!v[a[k]]&&!v[b[k]]){
				ia=1;
				puts("NO");
				break;
			}
				if(!v[a[k]])k=a[k];
				else k=b[k];
			}
			if(ia)break;
		}
		for(re int i=1;i<=26;++i){
			if(!v[i]){
				ia=1;
				puts("NO");
				break;
			}
		}
		if(ia)continue;
		puts("YES");
		for(re int i=1;i<=26;++i)putchar(ans[i]+'a'-1);
		putchar('\n');
	}
}
原文
存档评论1 条抓取于