-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfox and names.cpp
More file actions
96 lines (81 loc) · 1.4 KB
/
fox and names.cpp
File metadata and controls
96 lines (81 loc) · 1.4 KB
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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
#include <bits/stdc++.h>
using namespace std;
int visited[26] = {0};
int g[26][26] = {0};
stack<int> s;
void topological_sort(int v)
{
visited[v] = 1;
for (int i = 0; i < 26; i++)
{
if (g[v][i])
{
if (!visited[i])
topological_sort(i);
if (visited[i] == 1)
{
cout << "Impossible\n";
exit(0);
}
}
}
visited[v] = 2; // this is important
s.push(v);
}
int main()
{
int n;
cin >> n;
string words[100];
for (int i = 0; i < n; i++)
cin >> words[i];
int l1, l2, flag;
for (int i = 0; i < n; i++)
{
for (int j = i + 1; j < n; j++)
{
l1 = words[i].length();
l2 = words[j].length();
flag = 0;
for (int k = 0; k < min(l1, l2); k++)
{
if (words[i][k] != words[j][k])
{
g[words[i][k] - 97][words[j][k] - 97] = 1;
flag = 1;
break;
}
}
if (flag == 0)
{
if (l1 >= l2)
{
cout << "Impossible\n";
return 0;
}
}
}
}
for (int i = 0; i < 26; i++)
{
for (int j = 0; j < 26; j++)
{
if (g[i][j] && g[j][i])
{
cout << "Impossible\n";
return 0;
}
}
}
for (int i = 0; i < 26; i++)
{
if (!visited[i])
topological_sort(i);
}
while (!s.empty())
{
cout << char(s.top() + 97);
s.pop();
}
return 0;
}