add new solutions

This commit is contained in:
kanna5 2026-01-27 18:38:43 +09:00
parent 67cad91898
commit 81cc2d3ba6
No known key found for this signature in database
19 changed files with 693 additions and 14 deletions

View file

@ -0,0 +1,30 @@
package q3650
func minCost(n int, edges [][]int) int {
connections := make([][][2]int, n)
for i := range edges {
f, t, w := edges[i][0], edges[i][1], edges[i][2]
connections[f] = append(connections[f], [2]int{t, w})
connections[t] = append(connections[t], [2]int{f, w * 2})
}
minCost := make([]int, n)
minCost[0] = 1
queue := make([]int, 0, 1024)
queue = append(queue, 0)
for ; len(queue) > 0; queue = queue[1:] {
node := queue[0]
for i := range connections[node] {
next, cost := connections[node][i][0], connections[node][i][1]
if minCost[next] == 0 || minCost[node]+cost < minCost[next] {
minCost[next] = minCost[node] + cost
queue = append(queue, next)
}
}
}
return minCost[n-1] - 1
}
var _ = minCost

View file

@ -0,0 +1,65 @@
package q3651
import (
"math"
"slices"
)
func minCost(grid [][]int, k int) int {
w, h := len(grid[0]), len(grid)
gridVal := func(coord int) int { return grid[coord/w][coord%w] }
sortedCoords := make([]int, w*h)
for i := range sortedCoords {
sortedCoords[i] = (i)
}
slices.SortFunc(sortedCoords, func(a, b int) int { return gridVal(a) - gridVal(b) })
cache := make([]int32, w*h)
prevMinCosts := make([]int32, len(sortedCoords))
for tele := range k + 1 {
// Precompute min costs
if tele > 0 {
var curMin int32 = math.MaxInt32
i, j := 0, 0
for i < len(sortedCoords) {
curMin = min(curMin, cache[sortedCoords[i]])
i++
for j < i && (i == len(sortedCoords) || gridVal(sortedCoords[i]) > gridVal(sortedCoords[j])) {
prevMinCosts[sortedCoords[j]] = curMin
j++
}
}
}
for r := h - 1; r >= 0; r-- {
for c := w - 1; c >= 0; c-- {
if r == h-1 && c == w-1 {
continue
}
var val int32 = math.MaxInt32
if r+1 < h {
val = min(val, cache[(r+1)*w+c]+int32(grid[r+1][c]))
}
if c+1 < w {
val = min(val, cache[r*w+c+1]+int32(grid[r][c+1]))
}
if tele == 0 {
cache[r*w+c] = val
continue
}
// Find min cost with teleports
cache[r*w+c] = min(val, prevMinCosts[r*w+c])
}
}
}
return int(cache[0])
}
var _ = minCost