- 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
- 67 lines of Go from the credited upstream file 1594D.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 CF1594D(in io.Reader, _w io.Writer) {11 out := bufio.NewWriter(_w)12 defer out.Flush()13 var T, n, m, v, w int14 var s string15 for Fscan(in, &T); T > 0; T-- {16 Fscan(in, &n, &m)17 18 fa := make([]int, n)19 for i := range fa {20 fa[i] = i21 }22 dis := make([]uint8, n)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 merge := func(x, y int, d uint8) bool {33 fx, fy := find(x), find(y)34 if fx == fy {35 return dis[x]^dis[y] == d36 }37 dis[fx] = d ^ dis[y] ^ dis[x]38 fa[fx] = fy39 return true40 }41 42 ok := true43 for range m {44 Fscan(in, &v, &w, &s)45 if ok && !merge(v-1, w-1, s[1]&1) {46 ok = false47 }48 }49 if !ok {50 Fprintln(out, -1)51 continue52 }53 54 cnt := make([][2]int, n)55 for i := range n {56 cnt[find(i)][dis[i]]++57 }58 ans := 059 for _, c := range cnt {60 ans += max(c[0], c[1])61 }62 Fprintln(out, ans)63 }64}65 6667