-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy path834.cpp
More file actions
43 lines (41 loc) · 1.2 KB
/
Copy path834.cpp
File metadata and controls
43 lines (41 loc) · 1.2 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
class Solution {
vector<unordered_set<int>> graph;
vector<int> contains, ret;
vector<bool> visited;
int n;
public:
vector<int> sumOfDistancesInTree(int N, vector<vector<int>> &edges) {
n = N;
graph = vector<unordered_set<int>>(N, unordered_set<int>());
contains = vector<int>(N, 1);
ret = vector<int>(N, 0);
visited = vector<bool>(N, false);
for (auto &e:edges) {
graph[e[0]].insert(e[1]);
graph[e[1]].insert(e[0]);
}
DFS(0);
visited = vector<bool>(N, false);
CountDistance(0);
return ret;
}
void DFS(int root) {
visited[root] = true;
for (auto &node: graph[root]) {
if (visited[node])
continue;
DFS(node);
contains[root] += contains[node];
ret[root] += ret[node] + contains[node];
}
}
void CountDistance(int root) {
visited[root] = true;
for (auto &node:graph[root]) {
if (visited[node])
continue;
ret[node] = (ret[root] - ret[node] - contains[node] + n - contains[node]) + ret[node];
CountDistance(node);
}
}
};