Code: Select all

```
#include <iostream>
#include <string>
#include <vector>
#include <cstdlib>
using namespace std;
int main()
{
#ifndef ONLINE_JUDGE
freopen("in.txt", "r", stdin);
freopen("out.txt", "w", stdout);
#endif
string str;
vector<string> vec;
bool table[26][26] = {0};
int len;
while(getline(cin, str)) {
if(str == "#") {
if (vec.size()==1) {
cout << vec[0][0] << endl;
vec.clear();
for(int i=0; i<26; i++)
for(int j=0; j<26; j++)
table[i][j] = 0;
continue;
}
for(int i=0; i<vec.size()-1; i++) {
len = min( vec[i].length(), vec[i+1].length() );
for(int j=0; j<len; j++) {
if(vec[i][j] != vec[i+1][j]) {
table[ vec[i][j] - 'A' ][ vec[i+1][j] - 'A' ] = true;
break;
}
}
}
int starting=(vec[0][0]-65);
int k=starting;
string res="";
res+=(char)(starting+65);
char candidate;
// right part
while (true) {
candidate=-1;
for (int j=0; j<26; j++) {
if (table[k][j]) {
if (candidate==-1) {
candidate=j;
} else {
if (table[j][candidate]) {
candidate=j;
}
}
}
}
if (candidate!=-1) {
res+=(char)(candidate+65);
k=candidate;
} else {
break;
}
}
// left part
k=starting;
while (true) {
candidate=-1;
for (int j=0; j<26; j++) {
if (table[j][k]) {
if (candidate==-1) {
candidate=j;
} else {
if (table[candidate][j]) {
candidate=j;
}
}
}
}
if (candidate!=-1) {
res=(char)(candidate+65)+res;
k=candidate;
} else {
break;
}
}
/*
if (counter==0) {
cout << res;
counter=1;
} else {
cout << endl << res;
}
*/
cout << res << endl;
vec.clear();
for(int i=0; i<26; i++)
for(int j=0; j<26; j++)
table[i][j] = 0;
} else {
vec.push_back(str);
}
}
return 0;
}
```