Problem solution · Go

Codeforces 2060E — Graph Composition

Codeforces 2060E — Graph Composition: a Go solution using disjoint set union. Learn the idea, check the complexity, and read the full code, with credit to EndlessCheng Codeforces Go.

Technique
Disjoint set union
Source
EndlessCheng Codeforces Go
Length
72 lines
Start with the idea.

Try the problem first. If you get stuck, read the approach below, then write your own solution. The full code is at the bottom.

Approach

Disjoint set union

For Codeforces 2060E — Graph Composition, the implementation maintains connected components and merges them as relationships are processed.

  1. Give each element a component representative.
  2. Merge representatives when a connection is accepted.
  3. 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.

Source

Code and credit

This code comes from EndlessCheng Codeforces Go by Σndless (EndlessCheng) and is used under the MIT licence.

Full codeCodeforces 2060E — Graph Composition · GoGo
Use this to learn the idea, then write your own version.
package main import (	. "fmt"	"io") // https://github.com/EndlessChengtype uf60 []int func newUnionFind60(n int) uf60 {	fa := make(uf60, n)	for i := range fa {		fa[i] = i	}	return fa} func (u uf60) find(x int) int {	if u[x] != x {		u[x] = u.find(u[x])	}	return u[x]} func (u uf60) merge(from, to int) bool {	x, y := u.find(from), u.find(to)	if x == y {		return false	}	u[x] = y	return true} func (u uf60) same(x, y int) bool { return u.find(x) == u.find(y) } func cf2060E(in io.Reader, out io.Writer) {	var T, n, m1, m2 int	for Fscan(in, &T); T > 0; T-- {		Fscan(in, &n, &m1, &m2)		type edge struct{ v, w int }		es1 := make([]edge, m1)		for i := range es1 {			Fscan(in, &es1[i].v, &es1[i].w)		}		es2 := make([]edge, m2)		uf2 := newUnionFind60(n + 1)		for i := range es2 {			Fscan(in, &es2[i].v, &es2[i].w)			uf2.merge(es2[i].v, es2[i].w)		} 		ans := 0		uf1 := newUnionFind60(n + 1)		for _, e := range es1 {			if uf2.same(e.v, e.w) {				uf1.merge(e.v, e.w)			} else {				ans++			}		}		for _, e := range es2 {			if uf1.merge(e.v, e.w) {				ans++			}		}		Fprintln(out, ans)	}} //func main() { cf2060E(bufio.NewReader(os.Stdin), os.Stdout) } 

Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.

Buy me a coffee ↗