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 2 6 aloha arachnid dog gopher rat tiger 3 oak maple elm Sample Output aloha.arachnid.dog.gopher.rat.tiger *** |
题意:单词首尾连成欧拉通路。
解题:因为要记录路径,用结构体数组存边,然后就是判断等等。。
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <algorithm>
#include <cstdlib>
#include <map>
#include <vector>
#include <map>
#include <set>
#include <string>
using namespace std;
struct edge {
int u, vist, id; // vist表示这条边有没有背访问, id表示这条边对应第几个单词
};
vector<edge> vec[30];
string str[1010];
int vist[30], path[1010], par[30], out[30], in[30];
int n, top;
void init()
{
for(int i = 0; i < 26; i++) {
par[i] = i;
vec[i].clear();
}
memset(path, 0, sizeof(path));
memset(vist, 0, sizeof(vist));
memset(in, 0, sizeof(in));
memset(out, 0, sizeof(out));
return ;
}
int Find(int x)
{
return x==par[x] ? x : par[x]=Find(par[x]);
}
void unite(int x, int y)
{
int fx = Find(x);
int fy = Find(y);
if(fx == fy) return ;
par[fx] = par[fy];
return ;
}
void dfs(int s)
{
for(int i = 0; i < vec[s].size(); i++) {
if(!vec[s][i].vist) {
vec[s][i].vist = 1;
dfs(vec[s][i].u);
path[top++] = vec[s][i].id;
}
}
return ;
}
int main()
{
int T;
scanf("%d", &T);
while(T--) {
init();
scanf("%d", &n);
for(int i = 0; i < n; i++)
cin >> str[i];
sort(str, str+n);
for(int i = 0; i < n; i++) {
int a = str[i][0]-'a';
int b = str[i][str[i].size()-1]-'a';
out[a]++;
in[b]++;
unite(a, b);
edge es;
es.u = b, es.vist = 0, es.id = i;
vec[a].push_back(es);
}
int start = str[0][0] - 'a';
int c1=0, c2=0, c3=0, s=0;
// 欧拉通路判定
for(int i = 0; i < n; i++) {
if(in[i] || out[i] && (Find(i)==i)) s++;
if(in[i]-out[i]==1) c1++;
if(out[i]-in[i]==1) c2++, start = i;
if(abs(in[i]-out[i]) > 1) c3++;
}
// dfs记录路径
if(s==0 && ((c1==0 &&c2==0 && c3==0) || (c1==1 && c2==1 && c3==0))) {
top = 0;
dfs(start);
for(int i = top-1; i >= 0; i--) {
if(i == 0) cout << str[path[i]] << endl;
else cout << str[path[i]] << ".";
}
}
else puts("***");
}
}