- 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
- 98 lines of Go from the credited upstream file 698B.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 CF698B(_r io.Reader, _w io.Writer) {11 in := bufio.NewReader(_r)12 out := bufio.NewWriter(_w)13 defer out.Flush()14 type edge struct{ to, i int }15 16 var n, w int17 Fscan(in, &n)18 fa := make([]int, n+1)19 for i := range fa {20 fa[i] = i21 }22 var find func(int) int23 find = func(x int) int {24 if fa[x] != x {25 fa[x] = find(fa[x])26 }27 return fa[x]28 }29 merge := func(x, y int) { fa[find(x)] = find(y) }30 same := func(x, y int) bool { return find(x) == find(y) }31 a := make([]interface{}, n+1)32 g := make([][]edge, n+1)33 hasRoot := false34 for i := 1; i <= n; i++ {35 Fscan(in, &w)36 if i == w {37 hasRoot = true38 g[i] = append(g[i], edge{i, i})39 } else {40 merge(i, w)41 g[i] = append(g[i], edge{w, i})42 g[w] = append(g[w], edge{i, i})43 }44 a[i] = w45 }46 47 vs := []int{}48 for i := 1; i <= n; i++ {49 if i == fa[find(i)] {50 vs = append(vs, i)51 }52 }53 ans := len(vs)54 if hasRoot {55 ans--56 }57 Fprintln(out, ans)58 59 skipOne := true60 vis := make([]int8, n+1)61 var f func(int)62 f = func(v int) {63 vis[v] = 164 for _, e := range g[v] {65 w := e.to66 if t := vis[w]; t == 0 {67 f(w)68 } else if t == 2 || w == v {69 70 if t == 2 && !hasRoot {71 hasRoot = true72 a[e.i] = e.i73 continue74 }75 if w == v && skipOne {76 skipOne = false77 continue78 }79 80 if same(e.i, vs[0]) {81 vs[0], vs[1] = vs[1], vs[0]82 }83 merge(e.i, vs[0])84 a[e.i], vs = vs[0], vs[1:]85 }86 }87 vis[v] = 288 }89 for i := 1; i <= n; i++ {90 if vis[i] == 0 {91 f(i)92 }93 }94 Fprint(out, a[1:]...)95}96 9798