通过暴力比较任意两个字符串,确定字符之间的顺序关系,若i字符在j的前面则p[i][j] = 1;然后通过拓扑排序输出字符的顺序
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <map>
#include <vector>
#define maxn 1000005
#define MOD 1000000007
using namespace std;
typedef long long ll;
int n;
char str[105][105], p[30][30];
int cnt[30];
char v[30];
bool solve(char *k1, char *k2){
int len = min(strlen(k1), strlen(k2));
for(int i = 0; i < len; i++){
if(k1[i] != k2[i]){
int d1 = k1[i] - 'a';
int d2 = k2[i] - 'a';
if(p[d2][d1]){
return false;
}
if(p[d1][d2] == 0)
cnt[d2]++;
p[d1][d2] = 1;
return true;
}
}
if(strlen(k1) > strlen(k2))
return false;
return true;
}
int main(){
// freopen("in.txt", "r", stdin);
int n;
scanf("%d", &n);
for(int i = 0; i < n; i++)
scanf("%s", str[i]);
for(int i = 0; i < n; i++)
for(int j = i+1; j < n; j++){
if(solve(str[i], str[j]) == false){
puts("Impossible");
return 0;
}
}
for(int i = 0; i < 26; i++){
for(int j = 0; j < 26; j++){
if(cnt[j] == 0){
v[i] = j + 'a';
for(int h = 0; h < 26; h++){
if(p[j][h]){
cnt[h]--;
}
}
cnt[j] = -1;
break;
}
}
}
if(strlen(v) == 26)
printf("%s\n", v);
else
puts("Impossible");
return 0;
}