-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstring_stitch.cc
62 lines (59 loc) · 1.42 KB
/
string_stitch.cc
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
// http://www.practice.geeksforgeeks.org/problem-page.php?pid=173
#include <iostream>
#include <stack>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <vector>
using namespace std;
int main() {
int t;
cin >> t;
while (t--) {
int N;
cin >> N;
vector<vector<int>> adj;
adj.resize(N);
vector<string> strs;
strs.resize(N);
unordered_map<char, vector<int>> pre;
for (int i = 0; i < N; ++i) {
cin >> strs[i];
pre[strs[i][0]].push_back(i);
}
for (int i = 0; i < N; ++i) {
const string& str = strs[i];
auto it = pre.find(str[str.size() - 1]);
if (it != pre.end()) {
adj[i] = it->second;
}
}
bool all_visited = false;
for (int head = 0; head < N && !all_visited; ++head) {
stack<int> nodes;
nodes.push(head);
vector<int> visit(N, 0);
unordered_set<int> visited;
while (!nodes.empty()) {
int node = nodes.top();
if (visit[node] == 1) {
visit[node] = 2;
nodes.pop();
visited.insert(node);
continue;
}
visit[node] = 1;
for (int v : adj[node]) {
if (visit[v] == 0) nodes.push(v);
}
}
all_visited = visited.size() == N;
}
if (all_visited) {
cout << "Head to tail ordering is possible.\n";
} else {
cout << "Head to tail ordering is not possible.\n";
}
}
return 0;
}