-
Notifications
You must be signed in to change notification settings - Fork 50
/
Copy path510C. Fox And Names.cpp
70 lines (54 loc) · 1.01 KB
/
510C. Fox And Names.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
#include <iostream>
#include <vector>
#include <queue>
#include <string>
#include <algorithm>
using namespace std;
int in[26];
vector<int> g[26];
queue<int> q;
string s[100];
int main() {
int n, x, y;
cin >> n;
for (int i = 0; i < n; i++) cin >> s[i];
for (int i = 0; i + 1 < n; i++) {
int mn = min(s[i].length(), s[i + 1].length());
x = -1;
y = -1;
for (int j = 0; j < mn; j++)
if (s[i][j] != s[i + 1][j]) {
x = s[i][j];
y = s[i + 1][j];
break;
}
if (x == -1) {
if (s[i].length() > s[i + 1].length()) {
cout << "Impossible" << endl;
return 0;
}
continue;
}
x -= 'a';
y -= 'a';
g[x].push_back(y);
in[y]++;
}
for (int i = 0; i < 26; i++)
if (in[i] == 0)
q.push(i);
string res = "";
while (!q.empty()) {
int fr = q.front();
q.pop();
res += char(fr + 'a');
for (int i = 0; i < g[fr].size(); i++)
if (--in[g[fr][i]] == 0)
q.push(g[fr][i]);
}
if(res.length() == 26)
cout << res << endl;
else
cout << "Impossible" << endl;
return 0;
}