- 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
- 85 lines of Go from the credited upstream file 990G.go.
- The implementation visibly relies on sequence storage.
- 1 loop block 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 910func cf990G(in io.Reader, _w io.Writer) {11 out := bufio.NewWriter(_w)12 defer out.Flush()13 gcd := func(a, b int) int {14 for a != 0 {15 a, b = b%a, a16 }17 return b18 }19 20 const mx = 20000121 var cnt, time, fa, size, f [mx]int22 var n, now int23 Fscan(in, &n)24 a := make([]int, n)25 for i := range a {26 Fscan(in, &a[i])27 cnt[a[i]]++28 }29 es := [mx][][2]int{}30 for range n - 1 {31 var v, w int32 Fscan(in, &v, &w)33 v--34 w--35 g := gcd(a[v], a[w])36 es[g] = append(es[g], [2]int{v, w})37 }38 39 find := func(x int) int {40 rt := x41 for {42 if time[rt] != now {43 time[rt] = now44 fa[rt] = rt45 size[rt] = 146 }47 if fa[rt] == rt {48 break49 }50 rt = fa[rt]51 }52 for fa[x] != rt {53 fa[x], x = rt, fa[x]54 }55 return rt56 }57 58 for i := mx - 1; i > 0; i-- {59 now = i60 for j := i; j < mx; j += i {61 for _, e := range es[j] {62 x := find(e[0])63 y := find(e[1])64 if x != y {65 f[i] += size[x] * size[y]66 size[x] += size[y]67 fa[y] = x68 }69 }70 }71 for j := i * 2; j < mx; j += i {72 f[i] -= f[j]73 }74 }75 76 for i, v := range f[:] {77 v += cnt[i]78 if v > 0 {79 Fprintln(out, i, v)80 }81 }82}83 8485