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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
  | package main
import (
	"fmt"
	"math"
	"sort"
)
type Base struct {
	position int
	cost     int
}
type Solution struct{}
func (s Solution) MinCostToCoverHouses(houses []int, bases []int, costs []int, radius int) int {
	sort.Ints(houses)
	// Create a sorted slice of bases with costs
	n, m := len(houses), len(bases)
	basesWithCosts := make([]Base, m)
	for i := 0; i < m; i++ {
		basesWithCosts[i] = Base{
			position: bases[i],
			cost:     costs[i],
		}
	}
	sort.Slice(basesWithCosts, func(i, j int) bool {
		return basesWithCosts[i].position < basesWithCosts[j].position
	})
	// Initialize DP (Dynamic Programming) states
	dp := make([]int, n+1)
	for i := 1; i <= n; i++ {
		dp[i] = math.MaxInt32
	}
	// Iterate over each base for coverage
	for _, base := range basesWithCosts {
		coverStart := base.position - radius
		coverEnd := base.position + radius
		newDP := make([]int, n+1)
		copy(newDP, dp)
		for i := 0; i < n; i++ {
			if houses[i] >= coverStart && houses[i] <= coverEnd {
				newDP[i+1] = min(newDP[i+1], dp[i]+base.cost)
			}
		}
		dp = newDP
	}
	if dp[n] == math.MaxInt32 {
		return -1
	}
	return dp[n]
}
func min(a, b int) int {
	if a < b {
		return a
	}
	return b
}
func main() {
	houses := []int{1, 5, 10}
	bases := []int{3, 7, 11}
	costs := []int{1, 2, 3}
	radius := 3
	solution := Solution{}
	fmt.Println("Minimum cost:", solution.MinCostToCoverHouses(houses, bases, costs, radius))
}
  |