add new solutions
This commit is contained in:
parent
67cad91898
commit
51975f3386
24 changed files with 933 additions and 14 deletions
51
solutions/29/q2976/solution.go
Normal file
51
solutions/29/q2976/solution.go
Normal file
|
|
@ -0,0 +1,51 @@
|
|||
package q2976
|
||||
|
||||
import "math"
|
||||
|
||||
const INF int = math.MaxInt
|
||||
|
||||
func minimumCost(source string, target string, original []byte, changed []byte, cost []int) int64 {
|
||||
mat := make([][]int, 26)
|
||||
for i := range mat {
|
||||
mat[i] = make([]int, 26)
|
||||
mat[0][i] = INF
|
||||
}
|
||||
for i := 1; i < 26; i++ {
|
||||
copy(mat[i], mat[0])
|
||||
}
|
||||
|
||||
q := make([][3]int, 0, 2*len(original)) // src, dst, cost
|
||||
for i := range original {
|
||||
src, dst, cst := int(original[i]-'a'), int(changed[i]-'a'), cost[i]
|
||||
q = append(q, [3]int{src, dst, cst})
|
||||
mat[src][dst] = min(mat[src][dst], cst)
|
||||
}
|
||||
|
||||
for ; len(q) > 0; q = q[1:] {
|
||||
src, dst, cst := q[0][0], q[0][1], q[0][2]
|
||||
for next := range mat {
|
||||
if next == src || mat[dst][next] == INF {
|
||||
continue
|
||||
}
|
||||
nextCost := mat[dst][next] + cst
|
||||
if nextCost < mat[src][next] {
|
||||
mat[src][next] = nextCost
|
||||
q = append(q, [3]int{src, next, nextCost})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
minTotalCost := 0
|
||||
for i := range len(source) {
|
||||
if source[i] != target[i] {
|
||||
src, dst := source[i]-'a', target[i]-'a'
|
||||
if mat[src][dst] == INF {
|
||||
return -1
|
||||
}
|
||||
minTotalCost += mat[src][dst]
|
||||
}
|
||||
}
|
||||
return int64(minTotalCost)
|
||||
}
|
||||
|
||||
var _ = minimumCost
|
||||
Loading…
Add table
Add a link
Reference in a new issue