-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathDICTIONARY.cpp
More file actions
75 lines (61 loc) · 1.19 KB
/
Copy pathDICTIONARY.cpp
File metadata and controls
75 lines (61 loc) · 1.19 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
#include <bits/stdc++.h>
using namespace std;
bool graph[26][26];
bool visit[26];
int trans[26];
bool dfs(int pos, vector<int>& order)
{
visit[pos] = true;
for(int i=0; i < 26; i++)
if(graph[pos][i] && visit[i] == false)
dfs(i, order);
order.push_back(pos);
return true;
}
vector<int> topologySort()
{
vector<int> order;
memset(visit, false, sizeof(visit));
for(int i=0; i < 26; i++)
if(visit[i] == false)
dfs(i, order);
reverse(order.begin(), order.end());
for(int i=0; i < 26; i++)
for(int j=i+1; j < 26; j++)
if(graph[order[j]][order[i]])
return vector<int>();
return order;
}
int main()
{
int T;
cin >> T;
while(T--)
{
int N;
cin >> N;
vector<string> a(N);
for(int i=0; i < N; i++)
cin >> a[i];
memset(graph, false, sizeof(graph));
for(int i=1; i < N; i++)
{
int pos = 0;
while(a[i-1][pos] && a[i][pos] && a[i-1][pos] == a[i][pos])
pos++;
if(a[i-1][pos] == 0 || a[i][pos] == 0)
continue;
graph[a[i-1][pos]-'a'][a[i][pos]-'a'] = true;
}
vector<int> ans = topologySort();
if(ans.empty())
{
cout << "INVALID HYPOTHESIS\n";
continue;
}
for(auto p : ans)
cout << (char)(p + 'a');
cout << "\n";
}
return 0;
}