add new solutions
This commit is contained in:
parent
489fa73880
commit
0f5f9e331c
11 changed files with 539 additions and 0 deletions
60
solutions/3/q399/solution.go
Normal file
60
solutions/3/q399/solution.go
Normal file
|
|
@ -0,0 +1,60 @@
|
|||
package q399
|
||||
|
||||
func calcEquation(equations [][]string, values []float64, queries [][]string) []float64 {
|
||||
seen := make(map[[2]string]float64, len(equations)*8)
|
||||
queue := make([][2]string, 0, len(equations)*8)
|
||||
|
||||
for i := range equations {
|
||||
eq, val := equations[i], values[i]
|
||||
eq1, eq2 := [2]string{eq[0], eq[1]}, [2]string{eq[1], eq[0]}
|
||||
seen[eq1] = val
|
||||
seen[eq2] = 1 / val
|
||||
queue = append(queue, eq1, eq2)
|
||||
|
||||
seen[[2]string{eq[0], eq[0]}] = 1
|
||||
seen[[2]string{eq[1], eq[1]}] = 1
|
||||
}
|
||||
|
||||
for ; len(queue) > 0; queue = queue[1:] {
|
||||
eq := queue[0]
|
||||
val := seen[eq]
|
||||
|
||||
for i := range equations {
|
||||
var newVar string
|
||||
newVal := val
|
||||
switch eq[0] {
|
||||
case equations[i][0]:
|
||||
newVar = equations[i][1]
|
||||
newVal *= 1 / values[i]
|
||||
case equations[i][1]:
|
||||
newVar = equations[i][0]
|
||||
newVal *= values[i]
|
||||
default:
|
||||
continue
|
||||
}
|
||||
|
||||
newEq1 := [2]string{newVar, eq[1]}
|
||||
if _, ok := seen[newEq1]; !ok {
|
||||
seen[newEq1] = newVal
|
||||
queue = append(queue, newEq1)
|
||||
}
|
||||
newEq2 := [2]string{eq[1], newVar}
|
||||
if _, ok := seen[newEq2]; !ok {
|
||||
seen[newEq2] = 1 / newVal
|
||||
queue = append(queue, newEq2)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
ret := make([]float64, len(queries))
|
||||
for i := range queries {
|
||||
if val, ok := seen[[2]string{queries[i][0], queries[i][1]}]; ok {
|
||||
ret[i] = val
|
||||
} else {
|
||||
ret[i] = -1
|
||||
}
|
||||
}
|
||||
return ret
|
||||
}
|
||||
|
||||
var _ = calcEquation
|
||||
Loading…
Add table
Add a link
Reference in a new issue