代码如下,实在想不出来。
#include <bits/stdc++.h>
using namespace std;
vector<string> a;
vector<int> v;
vector<vector<pair<int, string>>> m(26);
vector<int> d(26);
int total;
string trace;
void dfs(int n)
{
if(total == int(a.size()-1)) {
cout << trace+"."+a[n] << endl;
exit(0);
} else {
string tmp = trace;
if(trace == "") trace = a[n];
else trace += "."+a[n];
int t = a[n][a[n].size()-1]-'a';
for(int i = 0; i < m[t].size(); i ++) {
if(v[m[t][i].first] != 1) {
v[m[t][i].first] = 1;
total ++;
dfs(m[t][i].first);
total --;
v[m[t][i].first] = 0;
}
}
trace = tmp;
}
}
bool cmp(pair<int, string> & a, pair<int, string> & b)
{
return a.second < b.second;
}
int main ( int argc, char *argv[] )
{
int N;
cin >> N;
a.resize(N);
v.resize(N);
for(int i = 0; i < N; i ++) {
cin >> a[i];
d[a[i][0]-'a'] ++;
d[a[i][a[i].size()-1]-'a'] ++;
}
sort(a.begin(), a.end());
int odd = 0;
int c = 0;
for(int i = 0; i < 26; i ++) {
if(d[i]%2 != 0) {
if(odd == 0) c = i;
odd ++;
}
}
if(odd != 0 && odd != 2) {
cout << "***" << endl;
return 0;
}
int mins = -1;
for(int i = 0; i < N; i ++) {
if(odd != 0 && mins == -1 && a[i][0] == 'a'+c) mins = i;
m[a[i][0]-'a'].push_back({i, a[i]});
}
if(mins == -1) mins = 0;
v[mins] = 1;
dfs(mins);
cout << "***" << endl;
return 0;
} /* ---------- end of function main ---------- */