- 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
- 112 lines of Go from the credited upstream file 917C.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 "math/bits"7 "slices"8)9 1011type matrix17 [][]int12 13func newMatrix17(n, m int) matrix17 {14 a := make(matrix17, n)15 for i := range a {16 a[i] = make([]int, m)17 for j := range a[i] {18 a[i][j] = 1e1819 }20 }21 return a22}23 24func (a matrix17) mul(b matrix17) matrix17 {25 c := newMatrix17(len(a), len(b[0]))26 for i, row := range a {27 for k, x := range row {28 if x == 1e18 {29 continue30 }31 for j, y := range b[k] {32 c[i][j] = min(c[i][j], x+y)33 }34 }35 }36 return c37}38 39func (a matrix17) powMul(n int, f0 matrix17) matrix17 {40 res := f041 for ; n > 0; n /= 2 {42 if n%2 > 0 {43 res = a.mul(res)44 }45 a = a.mul(a)46 }47 return res48}49 50func cf917C(in io.Reader, out io.Writer) {51 var x, k, n, q, t, ex int52 Fscan(in, &x, &k, &n, &q)53 c := make([]int, k)54 for i := range c {55 Fscan(in, &c[i])56 }57 58 59 mp := make([]int, 1<<k)60 for i := range mp {61 if bits.OnesCount(uint(i)) == x {62 mp[i] = t63 t++64 }65 }66 67 m := newMatrix17(t, t)68 for old := range 1 << k {69 if bits.OnesCount(uint(old)) != x {70 continue71 }72 if old&1 == 0 {73 m[mp[old>>1]][mp[old]] = 074 continue75 }76 nw := old >> 177 for s := uint(1<<k - 1 ^ nw); s > 0; s &= s - 1 {78 p := bits.TrailingZeros(s)79 m[mp[nw|1<<p]][mp[old]] = c[p]80 }81 }82 83 f := newMatrix17(t, 1)84 f[0][0] = 085 86 type pair struct{ p, w int }87 a := make([]pair, q)88 for i := range a {89 Fscan(in, &a[i].p, &a[i].w)90 }91 slices.SortFunc(a, func(a, b pair) int { return a.p - b.p })92 93 pre := 194 for _, p := range a {95 if p.p > n-x {96 ex += p.w97 continue98 }99 f = m.powMul(p.p-pre, f)100 pre = p.p101 for i, idx := range mp {102 if i%2 > 0 && bits.OnesCount(uint(i)) == x {103 f[idx][0] += p.w104 }105 }106 }107 f = m.powMul(n-x+1-pre, f)108 Fprint(out, f[0][0]+ex)109}110 111112