Catenyms
Description
A catenym is a pair of words separated by a period such that the last letter of the first word is the same as the last letter of the second. For example, the following are catenyms:
dog.gopher gopher.rat rat.tiger aloha.aloha arachnid.dog A compound catenym is a sequence of three or more words separated by periods such that each adjacent pair of words forms a catenym. For example, aloha.aloha.arachnid.dog.gopher.rat.tiger Given a dictionary of lower case words, you are to find a compound catenym that contains each of the words exactly once. Input
The first line of standard input contains t, the number of test cases. Each test case begins with 3 <= n <= 1000 - the number of words in the dictionary. n distinct dictionary words follow; each word is a string of between 1 and 20 lowercase letters on a line by itself.
Output
For each test case, output a line giving the lexicographically least compound catenym that contains each dictionary word exactly once. Output "***" if there is no solution.
Sample Input Sample Output Source |
[Submit] [Go Back] [Status] [Discuss]
题目大意:词语接龙,按照字典序从小到大排。
思路:单词两端字母看作节点,字符串看作边,结构体存图,先判断并查集,再判断欧拉回路,然后dfs逆序输出路径即可。
附上AC代码:
#include<iostream>
#include<string>
#include<algorithm>
#include<cstring>
#include<cstdio>
using namespace std;
const int maxn=26+5;
int par[maxn];
int vis[maxn];
int in[maxn],out[maxn];
int Stack[1010];
int top;
int t,n;
int in_num,out_num;
int num;
int flag;
int start;
string s[1010];
struct edges{
int fr,to;
int visit;
}edge[2500];
void init()
{
for(int i=1;i<27;i++)
{
par[i]=i;
in[i]=out[i]=0;
vis[i]=0;
}
memset(Stack,0,sizeof(Stack));
in_num=out_num=num=top=0;
flag=1;
}
int find(int a)
{
if(a==par[a])return a;
else return par[a]=find(par[a]);
}
void unite(int a,int b)
{
a=find(a);
b=find(b);
if(a==b)return ;
else if(a>b)
par[a]=b;
else
par[b]=a;
}
void euler_dfs(int a)
{
for(int i=0;i<n;i++)
if(edge[i].visit==0&&edge[i].fr==a)
{
edge[i].visit=1;
euler_dfs(edge[i].to);
Stack[top++]=i;
}
}
int main()
{
ios::sync_with_stdio(false);
scanf("%d",&t);
while(t--)
{
init();
scanf("%d",&n);
for(int i=0;i<n;i++)
cin>>s[i];
sort(s,s+n);
for(int i=0;i<n;i++)
{
int len=s[i].length();
int u=s[i][0]-'a'+1;
int v=s[i][len-1]-'a'+1;
in[v]++;
out[u]++;
edge[i].fr=u;
edge[i].to=v;
edge[i].visit=0;
vis[u]=vis[v]=1;
unite(u,v);
}
start=edge[0].fr;
for(int i =0;i<maxn;i++)
{
if(vis[i])
{
if(find(i)==i)
num++;
if(num>1){flag=0;break;}
}
}
int i;
if(flag)
{
for(i=1;i<27;i++)
{
if(vis[i])
{
if(in[i]==out[i])continue;
else if(in[i]-out[i]==1)in_num++;
else if(out[i]-in[i]==1){out_num++;start=i;}
else {flag=0;break;}
}
}
}
if((flag&&in_num==0&&out_num==0)||(flag&&in_num==1&&out_num==1))
{
euler_dfs(start);
cout<<s[Stack[top-1]];
for(int i=top-2;i>=0;i--)
cout<<"."<<s[Stack[i]];
printf("\n");
}
else
{
printf("***\n");
// cout<<in_num<<' '<<out_num<<' '<<num<<endl;
}
}
return 0;
}