- 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
- 87 lines of Go from the credited upstream file 1494D.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 "sort"8)9 1011func CF1494D(_r io.Reader, _w io.Writer) {12 in := bufio.NewReader(_r)13 out := bufio.NewWriter(_w)14 defer out.Flush()15 type pair struct{ i, j, v int }16 max := func(a, b int) int {17 if a > b {18 return a19 }20 return b21 }22 23 var n, v int24 Fscan(in, &n)25 fa := make([]int, n)26 var find func(int) int27 find = func(x int) int {28 if fa[x] != x {29 fa[x] = find(fa[x])30 }31 return fa[x]32 }33 a := make([]pair, 0, n*(n-1)/2)34 ans := make([]int, n)35 for i := 0; i < n; i++ {36 for j := 0; j < n; j++ {37 Fscan(in, &v)38 if i < j {39 a = append(a, pair{i, j, v})40 } else if i == j {41 ans[i] = v42 fa[i] = i43 }44 }45 }46 sort.Slice(a, func(i, j int) bool { a, b := a[i], a[j]; return a.v < b.v || a.v == b.v && a.i < b.i })47 pa := make([]int, n)48 for _, p := range a {49 if i, j := find(p.i), find(p.j); i == j {50 } else if max(ans[i], ans[j]) < p.v {51 ans = append(ans, p.v)52 f := len(fa)53 fa = append(fa, f)54 fa[f] = f55 fa[i] = f56 fa[j] = f57 pa = append(pa, f)58 pa[i] = f59 pa[j] = f60 } else if ans[i] == p.v {61 fa[j] = i62 pa[j] = i63 } else {64 fa[i] = j65 pa[i] = j66 }67 }68 Fprintln(out, len(ans))69 for _, v := range ans {70 Fprint(out, v, " ")71 }72 Fprintln(out)73 for i, f := range fa {74 if i == f {75 Fprintln(out, i+1)76 break77 }78 }79 for i, p := range pa {80 if i != p {81 Fprintln(out, i+1, p+1)82 }83 }84}85 8687