- 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
- 77 lines of Go from the credited upstream file 1166F.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 cf1166F(in io.Reader, _w io.Writer) {11 out := bufio.NewWriter(_w)12 defer out.Flush()13 var n, m, q, v, w, c int14 var op string15 Fscanln(in, &n, &m, &q, &q)16 17 fa := make([]int, n+1)18 for i := range fa {19 fa[i] = i20 }21 find := func(x int) int {22 rt := x23 for fa[rt] != rt {24 rt = fa[rt]25 }26 for fa[x] != rt {27 fa[x], x = rt, fa[x]28 }29 return rt30 }31 32 g := make([]map[int]bool, n+1)33 c2w := make([]map[int]int, n+1)34 for i := range g {35 g[i] = map[int]bool{}36 c2w[i] = map[int]int{}37 }38 add := func(v, w int) {39 g[find(v)][w] = true40 if c2w[v][c] == 0 {41 c2w[v][c] = w42 return43 }44 v = find(c2w[v][c])45 w = find(w)46 if v == w {47 return48 }49 if len(g[v]) > len(g[w]) {50 v, w = w, v51 }52 for x := range g[v] {53 g[w][x] = true54 }55 fa[v] = w56 }57 58 for range m {59 Fscanln(in, &v, &w, &c)60 add(v, w)61 add(w, v)62 }63 for range q {64 Fscanln(in, &op, &v, &w, &c)65 if op == "+" {66 add(v, w)67 add(w, v)68 } else if find(v) == find(w) || g[find(v)][w] {69 Fprintln(out, "Yes")70 } else {71 Fprintln(out, "No")72 }73 }74}75 7677