题目链接:https://codeforces.com/contest/510/problem/C
题目大意:给一些字符串,要求通过重新排序字母表使得这些字符串按照字典序排序
题目思路:当时昏了一直想着模拟,实际上很明显给出的是各字母的相对关系,所以建边进行拓扑排序即可
以下是代码:
#include<bits/stdc++.h>
using namespace std;
#define inf 0x3f3f3f3f
#define rep(i,a,b) for(int i=a;i<=b;i++)
#define per(i,a,b) for(int i=a;i>=b;i--)
#define ll long long
const int MAXN =2e3+5;
int n,du[MAXN];
char s[MAXN][MAXN];
vector<int>v[MAXN],g;
queue<int>q;
int main()
{
while(~scanf("%d",&n)){
while(!q.empty())q.pop();
g.clear();
int m=0;
rep(i,1,n){
scanf("%s",s[i]);
int len=strlen(s[i]);
m=max(m,len);
v[i].clear();
}
memset(du,0,sizeof(du));
int num=0,flag=0;
rep(i,1,n-1){
int len1=strlen(s[i]),len2=strlen(s[i+1]),mark=0;
for(int j=0;j<len1&&j<len2;j++){
if(s[i][j]!=s[i+1][j]){
mark=1;
v[s[i][j]].push_back(s[i+1][j]);
du[s[i+1][j]]++;
break;
}
}
if(!mark&&len1>len2){
flag=1;
break;
}
}
rep(i,'a','z'){
if(!du[i])q.push(i);
}
while(!q.empty()){
int u=q.front();
q.pop();
g.push_back(u);
num++;
int len=v[u].size();
rep(i,0,len-1){
int to=v[u][i];
du[to]--;
if(!du[to])q.push(to);
}
}
if(flag||num<26){
printf("Impossible\n");
}
else{
rep(i,0,25)printf("%c",g[i]);
cout<<endl;
}
}
return 0;
}