- 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
- 105 lines of Go from the credited upstream file 594D.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 910const mod94 = 1_000_000_00711 12type fenwick94 []int13 14func (f fenwick94) update(i, val int) {15 for ; i < len(f); i += i & -i {16 f[i] = f[i] * val % mod9417 }18}19 20func (f fenwick94) pre(i int) int {21 res := 122 for ; i > 0; i &= i - 1 {23 res = res * f[i] % mod9424 }25 return res26}27 28func cf594D(in io.Reader, _w io.Writer) {29 out := bufio.NewWriter(_w)30 defer out.Flush()31 const mx int = 1e6 + 132 lpf := [mx]int{1: 1}33 for i := 2; i < mx; i++ {34 if lpf[i] == 0 {35 for j := i; j < mx; j += i {36 if lpf[j] == 0 {37 lpf[j] = i38 }39 }40 }41 }42 inv := func(x int) int {43 res := 144 for n := mod94 - 2; n > 0; n /= 2 {45 if n%2 > 0 {46 res = res * x % mod9447 }48 x = x * x % mod9449 }50 return res51 }52 53 var n, q, l, r int54 Fscan(in, &n)55 a := make([]int, n)56 mul := 157 for i := range a {58 Fscan(in, &a[i])59 mul = mul * a[i] % mod9460 }61 invM := make([]int, n+1)62 invM[n] = inv(mul)63 for i := n - 1; i >= 0; i-- {64 invM[i] = invM[i+1] * a[i] % mod9465 }66 67 Fscan(in, &q)68 type pair struct{ l, i int }69 qs := make([][]pair, n+1)70 for i := range q {71 Fscan(in, &l, &r)72 qs[r] = append(qs[r], pair{l - 1, i})73 }74 75 ans := make([]int, q)76 t := make(fenwick94, n+1)77 for i := range t {78 t[i] = 179 }80 last := [mx]int{}81 mul = 182 for i, x := range a {83 i++84 mul = mul * x % mod9485 for x > 1 {86 p := lpf[x]87 for x /= p; x%p == 0; x /= p {88 }89 if last[p] > 0 {90 t.update(last[p], 1+inv(p-1))91 }92 t.update(i, 1-inv(p)+mod94)93 last[p] = i94 }95 for _, p := range qs[i] {96 ans[p.i] = mul * invM[p.l] % mod94 * t.pre(i) % mod94 * inv(t.pre(p.l)) % mod9497 }98 }99 for _, v := range ans {100 Fprintln(out, v)101 }102}103 104105