-
Notifications
You must be signed in to change notification settings - Fork 15
/
largest-distance-between-nodes-of-a-tree_test.cpp
112 lines (94 loc) · 2.75 KB
/
largest-distance-between-nodes-of-a-tree_test.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
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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
#include <bits/stdc++.h>
using namespace std;
#define DEBUG(x) \
do { \
std::cout << #x << ": " << x << " "; \
} while (0)
#define DEBUGL(x) \
do { \
std::cout << #x << ": " << x << "\n"; \
} while (0)
#define MOD 1000000007
template <typename T> void print_vector(vector<T> a) {
for (auto &i : a) {
cout << i << " ";
}
cout << "\n";
}
template <typename T> void print_matrix_2d(vector<vector<T>> a) {
int r = 0;
for (auto &i : a) {
cout << r << ": ";
for (auto &j : i) {
cout << j << " ";
}
r++;
cout << "\n";
}
cout << "\n";
}
int build_tree(const vector<int> &parents, vector<vector<int>> &tree) {
int n = parents.size();
tree.clear();
tree.resize(n, vector<int>());
int root_node = 0;
for (int node = 0; node < n; node++) {
if (parents[node] == -1) {
root_node = node;
continue;
}
tree[node].push_back(parents[node]);
tree[parents[node]].push_back(node);
}
return root_node;
}
int bfs(const vector<vector<int>> &tree, int start, int &end) {
unordered_set<int> visited;
queue<pair<int, int>> q;
int cur_level = 0;
int cur_node = start;
q.push({cur_node, cur_level});
while (!q.empty()) {
cur_node = q.front().first;
visited.insert(cur_node);
cur_level = q.front().second;
q.pop();
for (auto neighbour : tree[cur_node]) {
if (visited.count(neighbour) == 0) {
q.push({neighbour, cur_level + 1});
}
}
}
end = cur_node;
return cur_level;
}
// Time - O(N), Space - O(N)
int solve(const vector<int> &A) {
const vector<int> &parents = A;
vector<vector<int>> tree;
int root = build_tree(parents, tree);
int path_start, path_end;
bfs(tree, root, path_start);
int max_distance = bfs(tree, path_start, path_end);
return max_distance;
}
int main() {
// ios::sync_with_stdio(0);
// cin.tie(0);
vector<vector<int>> parents{
{-1, 0, 0, 0, 3, 1, 1, 2},
{-1, 0, 1, 2, 3},
{-1, 0, 1, 2, 1, 4, 5, 0, 3, 8},
};
vector<vector<int>> tree;
for (auto &p : parents) {
int root = build_tree(p, tree);
print_matrix_2d(tree);
int end;
DEBUGL(bfs(tree, root, end));
DEBUGL(end);
DEBUGL(solve(p));
cout << "\n\n";
}
return 0;
}