- 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
- 66 lines of Go from the credited upstream file 766D.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 CF766D(_r io.Reader, _w io.Writer) {11 in := bufio.NewReader(_r)12 out := bufio.NewWriter(_w)13 defer out.Flush()14 15 var n, m, q, d int16 var x, y string17 Fscan(in, &n, &m, &q)18 fa := make([]int, n)19 dis := make([]int, n)20 for i := range fa {21 fa[i] = i22 }23 var find func(int) int24 find = func(x int) int {25 if fa[x] != x {26 ffx := find(fa[x])27 dis[x] += dis[fa[x]]28 fa[x] = ffx29 }30 return fa[x]31 }32 delta := func(x, y int) int { return ((dis[x]-dis[y])%2 + 2) % 2 }33 merge := func(from, to int, d int) bool {34 if fFrom, fTo := find(from), find(to); fFrom != fTo {35 dis[fFrom] = d + dis[to] - dis[from]36 fa[fFrom] = fTo37 return true38 }39 return delta(from, to) == d40 }41 same := func(x, y int) bool { return find(x) == find(y) }42 43 id := make(map[string]int, n)44 for ; n > 0; n-- {45 Fscan(in, &x)46 id[x] = len(id)47 }48 for ; m > 0; m-- {49 Fscan(in, &d, &x, &y)50 if merge(id[x], id[y], d-1) {51 Fprintln(out, "YES")52 } else {53 Fprintln(out, "NO")54 }55 }56 for ; q > 0; q-- {57 Fscan(in, &x, &y)58 if a, b := id[x], id[y]; same(a, b) {59 Fprintln(out, delta(a, b)+1)60 } else {61 Fprintln(out, 3)62 }63 }64}65 66