- 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
- 81 lines of Go from the credited upstream file 1851G.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 "slices"8)9 10func cf1851G(in io.Reader, _w io.Writer) {11 out := bufio.NewWriter(_w)12 defer out.Flush()13 var T, n, m, q, v, w, e int14 for Fscan(in, &T); T > 0; T-- {15 Fscan(in, &n, &m)16 type pair struct{ v, i int }17 h := make([]pair, n)18 for i := range h {19 Fscan(in, &h[i].v)20 h[i].i = i21 }22 23 g := make([][]int, n)24 for ; m > 0; m-- {25 Fscan(in, &v, &w)26 v--27 w--28 if h[v].v < h[w].v {29 v, w = w, v30 }31 g[v] = append(g[v], w)32 }33 34 Fscan(in, &q)35 type data struct{ e, v, w, qid int }36 qs := make([]data, q)37 for i := range qs {38 Fscan(in, &v, &w, &e)39 v--40 w--41 qs[i] = data{e + h[v].v, v, w, i}42 }43 slices.SortFunc(qs, func(a, b data) int { return a.e - b.e })44 slices.SortFunc(h, func(a, b pair) int { return a.v - b.v })45 46 fa := make([]int, n)47 for i := range fa {48 fa[i] = i49 }50 var find func(int) int51 find = func(x int) int {52 if fa[x] != x {53 fa[x] = find(fa[x])54 }55 return fa[x]56 }57 58 ans := make([]bool, q)59 i := 060 for _, q := range qs {61 for ; i < n && h[i].v <= q.e; i++ {62 f := find(h[i].i)63 for _, w := range g[h[i].i] {64 fa[find(w)] = f65 }66 }67 ans[q.qid] = find(q.v) == find(q.w)68 }69 for _, b := range ans {70 if b {71 Fprintln(out, "YES")72 } else {73 Fprintln(out, "NO")74 }75 }76 Fprintln(out)77 }78}79 8081