- Give each element a component representative.
- Merge representatives when a connection is accepted.
- Answer connectivity or component queries from the compressed representatives.
Code notes
- 89 lines of Go from the credited upstream file 1850H.go.
- The implementation visibly relies on sequence storage.
- No explicit loop blocks detected.
Complexity
Account for every find and union operation; with path compression and ranked merging, the amortized cost is nearly constant per operation.
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 . "fmt"5 "io"6)7 89type unionFind50 struct {10 fa []int 11 dis []int 12}13 14func newUnionFind50(n int) unionFind50 {15 16 17 fa := make([]int, n)18 dis := make([]int, n)19 for i := range fa {20 fa[i] = i21 }22 return unionFind50{fa, dis}23}24 252627func (u unionFind50) find(x int) int {28 if u.fa[x] != x {29 root := u.find(u.fa[x])30 u.dis[x] += u.dis[u.fa[x]] 31 u.fa[x] = root32 }33 return u.fa[x]34}35 3637func (u unionFind50) same(x, y int) bool {38 return u.find(x) == u.find(y)39}40 414243func (u unionFind50) getRelativeDistance(from, to int) int {44 u.find(from)45 u.find(to)46 47 return u.dis[from] - u.dis[to]48}49 50515253func (u unionFind50) merge(from, to int, value int) bool {54 x, y := u.find(from), u.find(to)55 if x == y { 56 57 return u.dis[from]-u.dis[to] == value58 }59 60 61 62 63 64 65 u.dis[x] = value + u.dis[to] - u.dis[from] 66 u.fa[x] = y67 return true68}69 70func cf1850H(in io.Reader, out io.Writer) {71 var T, n, m, a, b, d int72 for Fscan(in, &T); T > 0; T-- {73 Fscan(in, &n, &m)74 uf := newUnionFind50(n + 1)75 ok := true76 for range m {77 Fscan(in, &a, &b, &d)78 ok = ok && uf.merge(b, a, d)79 }80 if ok {81 Fprintln(out, "YES")82 } else {83 Fprintln(out, "NO")84 }85 }86}87 8889