- 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
- 98 lines of Go from the credited upstream file 1185G2.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 8func cf1185G2(in io.Reader, out io.Writer) {9 const mod = 1_000_000_00710 add := func(v *int, w int) {11 *v = (*v + w) % mod12 }13 14 var n, tot, w, tp int15 Fscan(in, &n, &tot)16 17 f := make([][]int, n+2)18 for i := range f {19 f[i] = make([]int, tot+1)20 }21 f[0][0] = 122 g := make([][][]int, n+2)23 for i := range g {24 g[i] = make([][]int, n+2)25 for j := range g[i] {26 g[i][j] = make([]int, tot+1)27 }28 }29 g[0][0][0] = 130 31 cnt := [3]int{}32 for i := 0; i < n; i++ {33 Fscan(in, &w, &tp)34 tp--35 if tp == 0 {36 for j := cnt[0]; j >= 0; j-- {37 for t := tot; t >= w; t-- {38 add(&f[j+1][t], f[j][t-w])39 }40 }41 } else {42 is := [3]int{}43 is[tp] = 144 for j := cnt[1]; j >= 0; j-- {45 for k := cnt[2]; k >= 0; k-- {46 for t := tot; t >= w; t-- {47 add(&g[j+is[1]][k+is[2]][t], g[j][k][t-w])48 }49 }50 }51 }52 cnt[tp]++53 }54 55 fac := make([]int, n+1)56 fac[0] = 157 for i := 1; i <= n; i++ {58 fac[i] = fac[i-1] * i % mod59 }60 61 ans := 062 c := make([][][][3]int, cnt[0]+2)63 for i := range c {64 c[i] = make([][][3]int, cnt[1]+2)65 for j := range c[i] {66 c[i][j] = make([][3]int, cnt[2]+2)67 }68 }69 c[1][0][0][0] = 170 c[0][1][0][1] = 171 c[0][0][1][2] = 172 for i, mat := range c[:cnt[0]+1] {73 for j, row := range mat[:cnt[1]+1] {74 for k, comb := range row[:cnt[2]+1] {75 sum := 076 for t, fit := range f[i] {77 sum = (sum + fit*g[j][k][tot-t]) % mod78 }79 add(&ans, fac[i]*fac[j]%mod*fac[k]%mod*(comb[0]+comb[1]+comb[2])%mod*sum)80 81 for pre := 0; pre < 3; pre++ {82 for cur := 0; cur < 3; cur++ {83 if cur == pre {84 continue85 }86 is := [3]int{}87 is[cur] = 188 add(&c[i+is[0]][j+is[1]][k+is[2]][cur], comb[pre])89 }90 }91 }92 }93 }94 Fprint(out, ans)95}96 9798