- 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
- 91 lines of Go from the credited upstream file 60D.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 cf60D(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 buf := make([]byte, 4096)17 _i, _n := 0, 018 rc := func() byte {19 if _i == _n {20 _n, _ = in.Read(buf)21 if _n == 0 {22 return 023 }24 _i = 025 }26 b := buf[_i]27 _i++28 return b29 }30 rd := func() (x uint32) {31 b := rc()32 for ; '0' > b; b = rc() {33 }34 for ; '0' <= b; b = rc() {35 x = x*10 + uint32(b&15)36 }37 return38 }39 40 const mx = 10_000_00041 fa := [mx + 1]uint32{}42 find := func(x uint32) uint32 {43 rt := x44 for fa[rt] != rt {45 rt = fa[rt]46 }47 for fa[x] != rt {48 fa[x], x = rt, fa[x]49 }50 return rt51 }52 53 n := rd()54 merge := func(x, y uint32) {55 if fa[x] == 0 || fa[y] == 0 {56 return57 }58 x = find(x)59 y = find(y)60 if x != y {61 fa[x] = y62 n--63 }64 }65 66 for range n {67 v := rd()68 fa[v] = v69 }70 71 for i := 1; i*(i+2) <= mx; i += 2 {72 73 for j := i + 2; i*j <= mx && j*j-i*i <= mx*2; j += 2 {74 if gcd(i, j) > 1 {75 continue76 }77 a := uint32(i * j)78 b := uint32(j*j-i*i) / 279 c := uint32(i*i+j*j) / 280 merge(a, b)81 if c <= mx {82 merge(a, c)83 merge(b, c)84 }85 }86 }87 Fprint(out, n)88}89 9091