From 1eefbd4a19c44ed063e7419ad1a21d8ec0acfb1e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Khoa=20Hu=E1=BB=B3nh=20=28Daniel=29?= Date: Sun, 28 Apr 2024 23:43:01 +0700 Subject: [PATCH] Create main.go --- solution/834/main.go | 42 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 solution/834/main.go diff --git a/solution/834/main.go b/solution/834/main.go new file mode 100644 index 0000000..22f2c97 --- /dev/null +++ b/solution/834/main.go @@ -0,0 +1,42 @@ +package main + +package main + +func sumOfDistancesInTree(n int, edges [][]int) []int { + graph := make(map[int][]int) + count := make([]int, n) + res := make([]int, n) + + for _, edge := range edges { + u, v := edge[0], edge[1] + graph[u] = append(graph[u], v) + graph[v] = append(graph[v], u) + } + + var dfs1 func(cur, parent int) + dfs1 = func(cur, parent int) { + count[cur] = 1 + for _, child := range graph[cur] { + if child != parent { + dfs1(child, cur) + count[cur] += count[child] + res[cur] += res[child] + count[child] + } + } + } + + var dfs2 func(cur, parent int) + dfs2 = func(cur, parent int) { + for _, child := range graph[cur] { + if child != parent { + res[child] = res[cur] + n - 2*count[child] + dfs2(child, cur) + } + } + } + + dfs1(0, -1) + dfs2(0, -1) + + return res +}