Linear Solution
Intuition: Calculate minimum walk cost for each componentApproach: Union FindComplexity
Time complexity: O(N+E+Q)

Space complexity: O(N)
Code
# Intuition: Calculate minimum walk cost for each component
<!-- Describe your first thoughts on how to solve this problem. -->

# Approach: Union Find
<!-- Describe your approach to solving the problem. -->

# Complexity
- Time complexity: O(N+E+Q)
<!-- Add your time complexity here, e.g. $$O(n)$$ -->

- Space complexity: O(N)
<!-- Add your space complexity here, e.g. $$O(n)$$ -->

# Code
```golang []
func minimumCost(n int, edges [][]int, query [][]int) []int {
    uf := NewUF(n)
    for _, edge := range edges{
        uf.Union(edge[0], edge[1])
    }
    componentCost := map[int]int{}
    for _, edge := range edges{
        currComponentRoot := uf.Find(edge[0])
        if _, ok := componentCost[currComponentRoot]; !ok{
            componentCost[currComponentRoot] = edge[2]
        }else{
            componentCost[currComponentRoot] &= edge[2]
        }
    }
    ans := make([]int, len(query))
    for i, q := range query{
        source, target := q[0], q[1]
        rootSource := uf.Find(source)
        rootTarget := uf.Find(target)
        if rootSource != rootTarget{
            ans[i] = -1
        }else{
            ans[i] = componentCost[rootSource]
        }
    }
    return ans
}

type UF struct {
	root   []int
	weight []int
	count  int
}

func NewUF(size int) *UF {
	root := make([]int, size)
	weight := make([]int, size)
	count := size
	for i := 0; i < size; i++ {
		root[i] = i
		weight[i] = 1
	}
	return &UF{
		root:   root,
		weight: weight,
		count:  count,
	}
}

func (uf *UF) Find(x int) int {
	if x == uf.root[x] {
		return x
	}
	uf.root[x] = uf.Find(uf.root[x])
	return uf.root[x]
}

func (uf *UF) Union(x, y int) bool {
	rootX := uf.Find(x)
	rootY := uf.Find(y)
	if rootX == rootY {
		return true
	}
	if uf.weight[rootX] > uf.weight[rootY] {
		uf.root[rootY] = rootX
		uf.weight[rootX] += uf.weight[rootY]
	} else {
		uf.root[rootX] = rootY
		uf.weight[rootY] += uf.weight[rootX]
	}
	uf.count--
	return false
}

func (uf *UF) ComponentCount() int {
	return uf.count
}
```
['Union Find', 'Go']