- 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
- 55 lines of Go from the credited upstream file 2174C2.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 89func cf2174C2(in io.Reader, out io.Writer) {10 var T, n, m, mod int11 pow := func(x, n int) int {12 res := 113 for ; n > 0; n /= 2 {14 if n%2 > 0 {15 res = res * x % mod16 }17 x = x * x % mod18 }19 return res20 }21 22 for Fscan(in, &T); T > 0; T-- {23 Fscan(in, &n, &m, &mod)24 inv := make([]int, n+1)25 sum := make([]int, n+1)26 inv[0] = 127 inv[1] = pow(m, mod-2)28 for i := 2; i <= n; i++ {29 inv[i] = inv[i-1] % mod * inv[1] % mod30 }31 sum[0] = 132 for i := 1; i <= n; i++ {33 sum[i] = (sum[i-1] + inv[i]) % mod34 }35 36 ans := 037 f := make([]int, n+1)38 for i := 1; i <= n; i++ {39 f[i] = (n + 1 - i) * inv[i/2] % mod40 ans += f[i]41 }42 ans %= mod43 ans *= ans44 for i := 2; i <= n; i++ {45 l, r := 1-i%2, i/246 x := inv[r] * ((r-l+1)*2 - 1)47 y := (sum[r*2]-sum[r+l-1])*2 - inv[r+r]48 ans = (ans + (x-y)%mod*(n-i+1)) % mod49 }50 Fprintln(out, (ans+mod)%mod)51 }52}53 5455