- 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
- 101 lines of Go from the credited upstream file 1530D.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 cf1530D(_r io.Reader, _w io.Writer) {11 in := bufio.NewReader(_r)12 out := bufio.NewWriter(_w)13 defer out.Flush()14 15 var T, n, st int16 for Fscan(in, &T); T > 0; T-- {17 Fscan(in, &n)18 g := make([]int, n)19 deg := make([]int, n)20 for i := range g {21 Fscan(in, &g[i])22 g[i]--23 deg[g[i]]++24 }25 26 rg := make([][]int, n)27 f := make([]int, n)28 from := make([]int, n)29 for i := range from {30 from[i] = -131 }32 q := []int{}33 for i, d := range deg {34 if d == 0 {35 q = append(q, i)36 }37 }38 for len(q) > 0 {39 v := q[0]40 q = q[1:]41 w := g[v]42 rg[w] = append(rg[w], v)43 f[v]++44 if f[v] > f[w] {45 f[w] = f[v]46 from[w] = v47 }48 if deg[w]--; deg[w] == 0 {49 q = append(q, w)50 }51 }52 53 type path struct{ st, end int }54 chain := []path{}55 var rdfs func(int, bool)56 rdfs = func(v int, change bool) {57 if rg[v] == nil {58 st = v59 } else {60 for _, w := range rg[v] {61 if w != from[v] {62 rdfs(w, true)63 }64 }65 rdfs(from[v], false)66 }67 if change {68 chain = append(chain, path{st, v})69 }70 }71 for i0, d := range deg {72 if d == 0 {73 continue74 }75 ring := []int{i0}76 for v := g[i0]; v != i0; v = g[v] {77 deg[v] = 078 ring = append(ring, v)79 }80 for i, v := range ring {81 if rg[v] != nil {82 rdfs(v, false)83 chain = append(chain, path{st, ring[(i-1+len(ring))%len(ring)]})84 }85 }86 }87 88 for i, p := range chain {89 g[p.end] = chain[(i+1)%len(chain)].st90 }91 92 Fprintln(out, n-len(chain))93 for _, v := range g {94 Fprint(out, v+1, " ")95 }96 Fprintln(out)97 }98}99 100101