-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHackerrank-CutTheTree.cpp
More file actions
61 lines (51 loc) · 1.5 KB
/
Copy pathHackerrank-CutTheTree.cpp
File metadata and controls
61 lines (51 loc) · 1.5 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
//This file only contains the functions used for solving the problem.
//The main function is omitted for brevity.
class graph {
private:
unordered_map<int, unordered_set<int>> list;
public:
void add_vertex(int u) {
list[u] = unordered_set<int>();
}
void add_edge(int u, int v) {
list[u].insert(v);
list[v].insert(u);
}
unordered_set<int> get_neighbours(int u) {
return list[u];
}
};
int build(graph& g, int u, vector<int>& data, vector<int>& w, unordered_set<int>& visited, vector<int>& parent) {
if (visited.count(u) > 0) return 0;
int sum = data[u-1];
visited.insert(u);
for (int v: g.get_neighbours(u)) {
sum += build(g, v, data,w, visited, parent);
parent[v] = u;
}
w[u] = sum;
return sum;
}
int cutTheTree(vector<int>& data, vector<vector<int>>& edges) {
graph g;
for (int i = 1; i < data.size() + 1;++i) {
g.add_vertex(i);
}
for (const auto& edge: edges) {
g.add_edge(edge[0], edge[1]);
}
vector<int> w(data.size()+1);
unordered_set<int> visited;
vector<int> parent(data.size() + 1);
build(g, 1, data, w,visited, parent);
parent[1] = -1;
int min_diff = INT32_MAX;
for (const auto& edge: edges) {
int u = edge[0];
int v = edge[1];
if (parent[v] != u) swap(u, v);
u = 1;
min_diff = min(min_diff, abs(w[v] - (w[u] - w[v])));
}
return min_diff;
}