File tree 1 file changed +47
-0
lines changed
1 file changed +47
-0
lines changed Original file line number Diff line number Diff line change
1
+ class Solution {
2
+ const static int N = 1e4 + 7 ;
3
+ vector<int > adj[N];
4
+ int ans1[N], ans[N], nodes[N];
5
+ public:
6
+ void dfs1 (int node, int par) {
7
+ for (auto to : adj[node]) {
8
+ if (to != par) {
9
+ dfs1 (to, node);
10
+ nodes[node] += nodes[to];
11
+ ans1[node] += (ans1[to] + nodes[to]);
12
+ }
13
+ }
14
+
15
+ nodes[node]++;
16
+ }
17
+
18
+ void dfs2 (int node, int par, int to_p) {
19
+ ans[node] = ans1[node] + to_p + (nodes[0 ] - nodes[node]); // include the linkage
20
+ for (auto to : adj[node]) {
21
+ if (to != par) {
22
+ dfs2 (to, node, ans[node] - (ans1[to] + nodes[to]));
23
+ }
24
+ }
25
+ }
26
+
27
+ vector<int > sumOfDistancesInTree (int n, vector<vector<int >>& edges) {
28
+ for (auto v : edges) {
29
+ adj[v[0 ]].push_back (v[1 ]);
30
+ adj[v[1 ]].push_back (v[0 ]);
31
+ }
32
+
33
+ // dfs1
34
+ dfs1 (0 , -1 );
35
+
36
+ // dfs2
37
+ dfs2 (0 , -1 , 0 );
38
+
39
+ // result
40
+ vector<int > ansF;
41
+ for (int i = 0 ; i < n; i++) {
42
+ ansF.push_back (ans[i]);
43
+ }
44
+
45
+ return ansF;
46
+ }
47
+ };
You can’t perform that action at this time.
0 commit comments