- 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
- 67 lines of Go from the credited upstream file 2171G.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)8 910func cf2171G(in io.Reader, out io.Writer) {11 const mod = 1_000_00312 pow := func(x, n int) int {13 res := 114 for ; n > 0; n /= 2 {15 if n%2 > 0 {16 res = res * x % mod17 }18 x = x * x % mod19 }20 return res21 }22 f := [mod]int{1}23 for i := 1; i < mod; i++ {24 f[i] = f[i-1] * i % mod25 }26 27 var T, n int28 for Fscan(in, &T); T > 0; T-- {29 Fscan(in, &n)30 a := make([]uint, n)31 for i := range a {32 Fscan(in, &a[i])33 }34 35 k := 9936 b := make([]uint, n)37 for i, v := range a {38 Fscan(in, &b[i])39 k = min(k, bits.Len(b[i]/v)-1)40 }41 42 cnt := make([]uint, k+1)43 ans := 144 for i, v := range b {45 d := v>>k - a[i]46 cnt[0] += d47 ans = ans * pow(f[d], mod-2) % mod48 for v &= 1<<k - 1; v > 0; v &= v - 1 {49 cnt[k-bits.TrailingZeros(v)]++50 }51 }52 53 s := k54 for _, c := range cnt {55 s += int(c)56 if c < mod {57 ans = ans * f[c] % mod58 } else {59 ans = 060 }61 }62 Fprintln(out, s, ans)63 }64}65 6667