- 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
- 90 lines of Go from the credited upstream file 1325E.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 910func CF1325E(_r io.Reader, _w io.Writer) {11 const mx, inf int32 = 1e6, 1e912 lpf := [mx + 1]int32{1: 1}13 for i := int32(2); i <= mx; i++ {14 if lpf[i] == 0 {15 for j := i; j <= mx; j += i {16 if lpf[j] == 0 {17 lpf[j] = i18 }19 }20 }21 }22 23 g := make([][]int32, mx)24 var n, v int3225 in := bufio.NewReader(_r)26 for Fscan(in, &n); n > 0; n-- {27 Fscan(in, &v)28 ps := make([]int32, 0, 2)29 for v > 1 {30 p := lpf[v]31 cnt := 132 for v /= p; lpf[v] == p; v /= p {33 cnt++34 }35 if cnt&1 == 1 {36 ps = append(ps, p)37 }38 }39 if len(ps) == 0 {40 Fprint(_w, 1)41 return42 }43 if len(ps) == 1 {44 ps = append(ps, 1)45 }46 v, w := ps[0], ps[1]47 g[v] = append(g[v], w)48 g[w] = append(g[w], v)49 }50 51 ans := inf52 dist := make([]int32, mx)53 for i := range dist {54 dist[i] = -155 }56 type pair struct{ v, fa int32 }57 var p pair58 for st := int32(1); st < 1000; st++ {59 vs := []int32{st}60 dist[st] = 061 q := []pair{{st, -1}}62 o:63 for len(q) > 0 {64 p, q = q[0], q[1:]65 v, fa := p.v, p.fa66 for _, w := range g[v] {67 if dist[w] == -1 {68 dist[w] = dist[v] + 169 q = append(q, pair{w, v})70 vs = append(vs, w)71 } else if w != fa {72 if l := dist[w] + dist[v] + 1; l < ans {73 ans = l74 }75 break o76 }77 }78 }79 for _, v := range vs {80 dist[v] = -181 }82 }83 if ans == inf {84 ans = -185 }86 Fprint(_w, ans)87}88 8990