- Give each element a component representative.
- Merge representatives when a connection is accepted.
- Answer connectivity or component queries from the compressed representatives.
Code notes
- 72 lines of Go from the credited upstream file 2060E.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 uf60 []int10 11func newUnionFind60(n int) uf60 {12 fa := make(uf60, n)13 for i := range fa {14 fa[i] = i15 }16 return fa17}18 19func (u uf60) find(x int) int {20 if u[x] != x {21 u[x] = u.find(u[x])22 }23 return u[x]24}25 26func (u uf60) merge(from, to int) bool {27 x, y := u.find(from), u.find(to)28 if x == y {29 return false30 }31 u[x] = y32 return true33}34 35func (u uf60) same(x, y int) bool { return u.find(x) == u.find(y) }36 37func cf2060E(in io.Reader, out io.Writer) {38 var T, n, m1, m2 int39 for Fscan(in, &T); T > 0; T-- {40 Fscan(in, &n, &m1, &m2)41 type edge struct{ v, w int }42 es1 := make([]edge, m1)43 for i := range es1 {44 Fscan(in, &es1[i].v, &es1[i].w)45 }46 es2 := make([]edge, m2)47 uf2 := newUnionFind60(n + 1)48 for i := range es2 {49 Fscan(in, &es2[i].v, &es2[i].w)50 uf2.merge(es2[i].v, es2[i].w)51 }52 53 ans := 054 uf1 := newUnionFind60(n + 1)55 for _, e := range es1 {56 if uf2.same(e.v, e.w) {57 uf1.merge(e.v, e.w)58 } else {59 ans++60 }61 }62 for _, e := range es2 {63 if uf1.merge(e.v, e.w) {64 ans++65 }66 }67 Fprintln(out, ans)68 }69}70 7172