aboutsummaryrefslogtreecommitdiffstats
path: root/834/main.go
blob: c2392f0d6f2209b40cd951cafd35df351e0631ee (plain) (blame)
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
package main

import "fmt"

func dfs(node int, parent int, adjList map[int][]int, count []int, result []int) {
	for _, child := range adjList[node] {
		if child == parent {
			continue
		}

		dfs(child, node, adjList, count, result)
		count[node] += count[child]
		result[node] += result[child] + count[child]
	}
}

func dfs2(node int, parent int, adjList map[int][]int, count []int, result []int) {
	for _, child := range adjList[node] {
		if child == parent {
			continue
		}

		result[child] = result[node] - count[child] + len(count) - count[child]
		dfs2(child, node, adjList, count, result)
	}
}

func sumOfDistancesInTree(n int, edges [][]int) []int {
	adjList := make(map[int][]int)

	for _, edge := range edges {
		adjList[edge[0]] = append(adjList[edge[0]], edge[1])
		adjList[edge[1]] = append(adjList[edge[1]], edge[0])
	}

	count := make([]int, n)
	for i := 0; i < len(count); i++ {
		count[i] = 1
	}

	result := make([]int, n)

	dfs(0, -1, adjList, count, result)
	dfs2(0, -1, adjList, count, result)

	return result
}

func main() {
	fmt.Println("vim-go")
}