forked from AnasImloul/Leetcode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathNumber Of Ways To Reconstruct A Tree.cpp
63 lines (53 loc) · 1.55 KB
/
Number Of Ways To Reconstruct A Tree.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
class Solution {
public:
int checkWays(vector<vector<int>>& pairs) {
unordered_map<int, unordered_set<int>> adj;
for (int i = 0; i < pairs.size(); i++) {
adj[pairs[i][0]].emplace(pairs[i][1]);
adj[pairs[i][1]].emplace(pairs[i][0]);
}
priority_queue<pair<int, int>> q;
for (auto& [x, arr] : adj) {
q.push({arr.size(), x});
}
int n = q.size();
bool multiple = false;
unordered_set<int> seen;
while (!q.empty()) {
auto [sz, v] = q.top();
q.pop();
int u = 0;
int usz = n + 1;
if (!seen.empty()) {
for (auto x : adj[v]) {
if (adj[x].size() < usz && seen.count(x)) {
u = x;
usz = adj[x].size();
}
}
}
seen.emplace(v);
if (u == 0) {
if (sz != (n - 1)) {
return 0;
}
continue;
}
for (auto x : adj[v]) {
if (x == u) {
continue;
}
if (!adj[u].count(x)) {
return 0;
}
}
if (usz == sz) {
multiple = true;
}
}
if (multiple) {
return 2;
}
return 1;
}
};