- 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
- 76 lines of Go from the credited upstream file 402D.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 "math/bits"8)9 1011func CF402D(_r io.Reader, out io.Writer) {12 in := bufio.NewReader(_r)13 gcd := func(a, b int) int {14 for a != 0 {15 a, b = b%a, a16 }17 return b18 }19 20 var n, m, v, g, ans int21 Fscan(in, &n, &m)22 a := make([]int, n)23 gs := make([]int, n)24 for i := range a {25 Fscan(in, &a[i])26 g = gcd(g, a[i])27 gs[i] = g28 }29 bad := make(map[int]bool, m)30 for ; m > 0; m-- {31 Fscan(in, &v)32 bad[v] = true33 }34 35 f := func(x int) (res int) {36 k := bits.TrailingZeros(uint(x))37 if bad[2] {38 res -= k39 } else {40 res += k41 }42 x >>= k43 for i := 3; i*i <= x; i += 2 {44 for x%i == 0 {45 x /= i46 if bad[i] {47 res--48 } else {49 res++50 }51 }52 }53 if x > 1 {54 if bad[x] {55 res--56 } else {57 res++58 }59 }60 return61 }62 for _, v := range a {63 ans += f(v)64 }65 g = 166 for i := n - 1; i >= 0; i-- {67 if res := f(gs[i] / g); res < 0 {68 ans -= (i + 1) * res69 g = gs[i]70 }71 }72 Fprint(out, ans)73}74 7576