- 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
- 75 lines of Go from the credited upstream file 1172C2.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 "bufio"5 . "fmt"6 "io"7)8 910func cf1172C2(in io.Reader, _w io.Writer) {11 out := bufio.NewWriter(_w)12 defer out.Flush()13 const mod = 99824435314 pow := func(x, n int) int {15 res := 116 for ; n > 0; n /= 2 {17 if n%2 > 0 {18 res = res * x % mod19 }20 x = x * x % mod21 }22 return res23 }24 25 var n, m int26 Fscan(in, &n, &m)27 a := make([]int, n)28 for i := range a {29 Fscan(in, &a[i])30 }31 w := make([]int, n)32 s := [2]int{}33 for i := range w {34 Fscan(in, &w[i])35 s[a[i]] += w[i]36 }37 38 f := make([][]int, m+2)39 g := make([][]int, m+2)40 for i := range f {41 f[i] = make([]int, m+2)42 g[i] = make([]int, m+2)43 }44 for j := 0; j <= m; j++ {45 f[j][m-j] = 146 g[j][m-j] = 147 }48 for i := m - 1; i >= 0; i-- {49 for j := 0; j <= i; j++ {50 k := i - j51 if k > s[0] {52 continue53 }54 s1 := s[1] + j55 s0 := s[0] - k56 sum := s1 + s057 inv := pow(sum, mod-2)58 f[j][k] = (2*f[j+1][k] + (s1-1)*f[j+1][k] + s0*f[j][k+1]) % mod59 f[j][k] = f[j][k] * inv % mod60 g[j][k] = ((s0-1)*g[j][k+1] + s1*g[j+1][k]) % mod61 g[j][k] = g[j][k] * inv % mod62 }63 }64 65 for i := 0; i < n; i++ {66 if a[i] > 0 {67 Fprintln(out, f[0][0]*w[i]%mod)68 } else {69 Fprintln(out, g[0][0]*w[i]%mod)70 }71 }72}73 7475