题目链接:http://codeforces.com/problemset/problem/510/C?csrf_token=baadfd2935ac90d344554ddd90621166
Input
3
rivest
shamir
adleman
Output
bcdefghijklmnopqrsatuvwxyz
Input
10
tourist
petr
wjmzbmr
yeputons
vepifanov
scottwu
oooooooooooooooo
subscriber
rowdark
tankengineer
Output
Impossible
Input
10
petr
egor
endagorion
feferivan
ilovetanyaromanova
kostka
dmitriyh
maratsnowbear
bredorjaguarturnik
cgyforever
Output
aghjlnopefikdmbcqrstuvwxyz
Input
7
car
care
careful
carefully
becarefuldontforgetsomething
otherwiseyouwillbehacked
goodluck
Output
acbdefhijklmnogpqrstuvwxyz
题意:给出按字典序排序好的字符串(并不一定是),问是否能写出字典序来,如果不能就输出Impossible,能就输出一种满足题意的字典序。
当给出的顺序出现环的时候,或者有串的前缀出现在串的后面时(比如abc出现在ab的前面),出现错误。
<mark>自我警示:添括号时一定要把范围搞对~~~</mark> wa了一晚上
#include<iostream>
#include<cstdio>
#include<queue>
#include<cstring>
#include<algorithm>
using namespace std;
string s[105];
bool G[30][30];
int indeg[30];
bool book[30];
queue<int> q;
queue<char>qs;
int main() {
int n;
cin>>n;
for(int i=1; i<=n; i++)
cin>>s[i];
bool flag=true;
for(int i=1; i<n; i++) {
int m=min(s[i].size(),s[i+1].size());
for(int j=0; j<m; j++) {
if(j==m-1&&s[i][j]==s[i+1][j]) {
if(s[i].size()>s[i+1].size()) {
flag=false;
break;
}
}
if(s[i][j]!=s[i+1][j]) {
if(!G[s[i][j]-'a'][s[i+1][j]-'a']) {
G[s[i][j]-'a'][s[i+1][j]-'a']=true;
indeg[s[i+1][j]-'a']++;
}
break;
}
}
if(!flag) break;
}
if(flag) {
int cnt=0;
for(int k=1; k<=26; k++) {
for(int i=0; i<26; i++) {
if(indeg[i]==0) {
cnt++;
indeg[i]--;
qs.push('a'+i);
for(int j=0; j<26; j++) {
if(G[i][j]) {
G[i][j]=false;
indeg[j]--;
}
}
break;
}
}
}
if(cnt<26) printf("Impossible\n");
else {
while(!qs.empty()) {
printf("%c",qs.front());
qs.pop();
}
printf("\n");
}
} else
printf("Impossible\n");
return 0;
}