首页 > 其他 > 详细

492. 单词游戏

时间:2019-07-15 12:59:17      阅读:98      评论:0      收藏:0      [点我收藏+]

【题目描述】:

有 N 个盘子,每个盘子上写着一个仅由小写字母组成的英文单词。你需要给这些盘子安排一个合适的顺序,使得相邻两个盘子中,前一个盘子上单词的末字母等于后一个盘子上单词的首字母。请你编写一个程序,判断是否能达到这一要求。如果能,请给出一个合适的顺序。

【输入描述】:

多组数据。第一行给出数据组数T,每组数据第一行给出盘子数量N,接下去N行给出小写字母字符串,一种字符串可能出现多次。

【输出描述】:

若存在一组合法解输出“Ordering is possible.”,否则输出“The door cannot be opened.”。

【样例输入】:

3
2
acm
ibm
3
acm
malform
mouse
2
ok
ok

【样例输出】:

The door cannot be opened.
Ordering is possible.
The door cannot be opened.

【时间限制、数据范围及描述】:

时间:1s 空间:64M

1<=N<=10^5;|S|<=1000

 

 

#include<algorithm>
#include<iostream>
#include<cstring>
#include<cstdio>
#include<cmath>
#include<queue>
using namespace std;
char s[1001];
int t,n,m,a,b,c;
int fa[50],u[50],v[50];
int find(int x){
	return fa[x]==x?x:fa[x]=find(fa[x]);
}
int main(){
	scanf("%d",&t);
	while(t--){
		memset(u,0,sizeof u);
		memset(v,0,sizeof v);
		scanf("%d",&n);
		a=b=c=0;
		for(int i=1;i<=30;i++){
			fa[i]=i;
		}
		for(int i=1;i<=n;i++){
			scanf("%s",s+1);
			m=strlen(s+1);
			int l=s[1]-‘a‘+1,r=s[m]-‘a‘+1;
			fa[find(l)]=find(r);
			u[l]++;
			v[r]++;
		}
		for(int i=1;i<=26;i++){
			if(((u[i]||v[i])&&(find(i)==i))||u[i]-v[i]>1||u[i]-v[i]<-1){
				a++;
			}
		}
		if(a>1){
			puts("The door cannot be opened.");
			continue;
		}
		for(int i=1;i<=26;i++){
			if(u[i]>v[i]){
				b++;
			}
			else if(u[i]<v[i]){
				c++;
			}
		}
		if(b!=c||b>1){
			puts("The door cannot be opened.");
			continue;
		}
		puts("Ordering is possible.");
	}
	return 0;
}

  

492. 单词游戏

原文:https://www.cnblogs.com/xiongchongwen/p/11188132.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!