- 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
- 136 lines of Go from the credited upstream file 514E.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 "slices"7)8 910const mod14 = 1_000_000_00711 12func pow14(x, n int) int {13 res := 114 for ; n > 0; n /= 2 {15 if n%2 > 0 {16 res = res * x % mod1417 }18 x = x * x % mod1419 }20 return res21}22 23func berlekampMassey14(a []int) (coef []int) {24 var preC []int25 preI, preD := -1, 026 for i, v := range a {27 d := v28 for j, c := range coef {29 d = (d - c*a[i-1-j]) % mod1430 }31 if d == 0 {32 continue33 }34 35 if preI < 0 {36 coef = make([]int, i+1)37 preI, preD = i, d38 continue39 }40 41 bias := i - preI42 oldLen := len(coef)43 newLen := bias + len(preC)44 var tmp []int45 if newLen > oldLen {46 tmp = slices.Clone(coef)47 coef = slices.Grow(coef, newLen-oldLen)[:newLen]48 }49 50 delta := d * pow14(preD, mod14-2) % mod1451 coef[bias-1] = (coef[bias-1] + delta) % mod1452 for j, c := range preC {53 coef[bias+j] = (coef[bias+j] - delta*c) % mod1454 }55 56 if newLen > oldLen {57 preC = tmp58 preI, preD = i, d59 }60 }61 62 return63}64 65func kitamasa14(coef, a []int, n int) (ans int) {66 defer func() { ans = (ans%mod14 + mod14) % mod14 }()67 if n < len(a) {68 return a[n]69 }70 71 k := len(coef)72 if k == 0 {73 return74 }75 if k == 1 {76 return a[0] * pow14(coef[0], n)77 }78 79 compose := func(a, b []int) []int {80 c := make([]int, k)81 for _, v := range a {82 for j, w := range b {83 c[j] = (c[j] + v*w) % mod1484 }85 bk1 := b[k-1]86 for j := k - 1; j > 0; j-- {87 b[j] = (b[j-1] + bk1*coef[j]) % mod1488 }89 b[0] = bk1 * coef[0] % mod1490 }91 return c92 }93 94 resC := make([]int, k)95 resC[0] = 196 c := make([]int, k)97 c[1] = 198 for ; n > 0; n /= 2 {99 if n%2 > 0 {100 resC = compose(c, resC)101 }102 c = compose(c, slices.Clone(c))103 }104 105 for i, c := range resC {106 ans = (ans + c*a[i]) % mod14107 }108 return109}110 111func cf514E(in io.Reader, out io.Writer) {112 var n, x, v int113 Fscan(in, &n, &x)114 const mx = 100115 cnt := [mx + 1]int{}116 for range n {117 Fscan(in, &v)118 cnt[v]++119 }120 121 f := make([]int, mx*2+2)122 f[0] = 1123 for i := 1; i < len(f); i++ {124 f[i] = 1125 for j, c := range cnt[1 : min(i, mx)+1] {126 f[i] += c * f[i-1-j]127 }128 f[i] %= mod14129 }130 coef := berlekampMassey14(f)131 slices.Reverse(coef)132 Fprint(out, kitamasa14(coef, f, x))133}134 135136