- 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
- 92 lines of Go from the credited upstream file 891C.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 CF891C(_r io.Reader, _w io.Writer) {11 out := bufio.NewWriter(_w)12 defer out.Flush()13 _i, buf := 1<<12, make([]byte, 1<<12)14 rc := func() byte {15 if _i == 1<<12 {16 _r.Read(buf)17 _i = 018 }19 b := buf[_i]20 _i++21 return b22 }23 r := func() (x int) {24 b := rc()25 for ; '0' > b; b = rc() {26 }27 for ; '0' <= b; b = rc() {28 x = x*10 + int(b&15)29 }30 return31 }32 33 n, m := r(), r()34 fa := make([]int, n+1)35 for i := range fa {36 fa[i] = i37 }38 var find func(int) int39 find = func(x int) int {40 if fa[x] != x {41 fa[x] = find(fa[x])42 }43 return fa[x]44 }45 type edge struct{ v, w, wt, fv, fw int }46 es := make([]edge, m)47 ids := make([][]int, 5e5+1)48 for i := range es {49 es[i] = edge{r(), r(), r(), 0, 0}50 ids[es[i].wt] = append(ids[es[i].wt], i)51 }52 for _, ids := range ids {53 for _, id := range ids {54 55 es[id].fv = find(es[id].v)56 es[id].fw = find(es[id].w)57 }58 for _, id := range ids {59 fa[find(es[id].v)] = find(es[id].w)60 }61 }62 63 faMap := map[int]int{}64 find = func(x int) int {65 if fx, ok := faMap[x]; ok && fx != x {66 faMap[x] = find(fx)67 return faMap[x]68 }69 return x70 }71o:72 for q := r(); q > 0; q-- {73 faMap = map[int]int{}74 for k := r(); k > 0; k-- {75 i := r() - 176 77 v, w := find(es[i].fv), find(es[i].fw)78 if v == w {79 Fprintln(out, "NO")80 for k--; k > 0; k-- {81 r()82 }83 continue o84 }85 faMap[v] = w86 }87 Fprintln(out, "YES")88 }89}90 9192