- 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
- 63 lines of Go from the credited upstream file 1986G2.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 cf1986G2(in io.Reader, out io.Writer) {10 gcd := func(a, b int) int {11 for a != 0 {12 a, b = b%a, a13 }14 return b15 }16 const mx = 50000117 ds := [mx][]uint32{}18 for i := uint32(1); i < mx; i++ {19 for j := i; j < mx; j += i {20 ds[j] = append(ds[j], i)21 }22 }23 24 var T, n, v int25 for Fscan(in, &T); T > 0; T-- {26 Fscan(in, &n)27 ans := 028 p2i := make([][]uint32, n+1)29 i2p := make([][]uint32, n+1)30 for i := 1; i <= n; i++ {31 Fscan(in, &v)32 g := gcd(v, i)33 p, i := v/g, i/g34 if i == 1 {35 ans--36 }37 p2i[p] = append(p2i[p], uint32(i))38 i2p[i] = append(i2p[i], uint32(p))39 }40 cnt := make([]uint32, n+1)41 for i := 1; i <= n; i++ {42 for pj := i; pj <= n; pj += i {43 for _, j := range p2i[pj] {44 cnt[j]++45 }46 }47 for _, pi := range i2p[i] {48 for _, j := range ds[pi] {49 ans += int(cnt[j])50 }51 }52 for pj := i; pj <= n; pj += i {53 for _, j := range p2i[pj] {54 cnt[j]--55 }56 }57 }58 Fprintln(out, ans/2)59 }60}61 6263