- Translate each rule into one explicit state update.
- Maintain the invariant after every processed item.
- Return the accumulated state once all relevant input has been handled.
Code notes
- 78 lines of Go from the credited upstream file 351C.go.
- The implementation visibly relies on sequence storage.
- No explicit loop blocks detected.
Complexity
Count the number and nesting of passes over the input, then include the maintained containers in the memory estimate.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1package main2 3import (4 . "fmt"5 "io"6)7 89type matrix51 [][]int10 11func newMatrix51(n, m int) matrix51 {12 a := make(matrix51, n)13 for i := range a {14 a[i] = make([]int, m)15 for j := range a[i] {16 a[i][j] = 1e1817 }18 }19 return a20}21 22func (a matrix51) mul(b matrix51) matrix51 {23 c := newMatrix51(len(a), len(b[0]))24 for i, row := range a {25 for k, x := range row {26 if x == 1e18 {27 continue28 }29 for j, y := range b[k] {30 c[i][j] = min(c[i][j], x+y)31 }32 }33 }34 return c35}36 37func (a matrix51) powMul(n int, f0 matrix51) matrix51 {38 res := f039 for ; n > 0; n /= 2 {40 if n%2 > 0 {41 res = a.mul(res)42 }43 a = a.mul(a)44 }45 return res46}47 48func cf351C(in io.Reader, out io.Writer) {49 var n, m int50 Fscan(in, &n, &m)51 a := make([]struct{ l, r int }, n)52 for i := range a {53 Fscan(in, &a[i].l)54 }55 for i := range a {56 Fscan(in, &a[i].r)57 }58 59 mt := newMatrix51(n+1, n+1)60 for i, row := range mt {61 row[i] = 062 }63 for _, p := range a {64 t := newMatrix51(n+1, n+1)65 for i := range n {66 t[i+1][i] = p.l67 t[i][i+1] = p.r68 }69 mt = t.mul(mt)70 }71 72 f0 := newMatrix51(n+1, 1)73 f0[0][0] = 074 Fprint(out, mt.powMul(m, f0)[0][0])75}76 7778