Problem solution · Go

Codeforces 1850H — The Third Letter

Codeforces 1850H — The Third Letter: 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
89 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 1850H — The Third Letter, 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

  • 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.

Source

Code and credit

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

Full codeCodeforces 1850H — The Third Letter · GoGo
Use this to learn the idea, then write your own version.
package main import (	. "fmt"	"io") // 模板来源 https://leetcode.cn/circle/discuss/mOr1u6/type unionFind50 struct {	fa  []int // 代表元	dis []int // dis[x] 表示 x 到(x 所在集合的)代表元的距离} func newUnionFind50(n int) unionFind50 {	// 一开始有 n 个集合 {0}, {1}, ..., {n-1}	// 集合 i 的代表元是自己,自己到自己的距离是 0	fa := make([]int, n)	dis := make([]int, n)	for i := range fa {		fa[i] = i	}	return unionFind50{fa, dis}} // 返回 x 所在集合的代表元// 同时做路径压缩func (u unionFind50) find(x int) int {	if u.fa[x] != x {		root := u.find(u.fa[x])		u.dis[x] += u.dis[u.fa[x]] // 递归更新 x 到其代表元的距离		u.fa[x] = root	}	return u.fa[x]} // 判断 x 和 y 是否在同一个集合(同普通并查集)func (u unionFind50) same(x, y int) bool {	return u.find(x) == u.find(y)} // 计算从 from 到 to 的相对距离// 调用时需保证 from 和 to 在同一个集合中,否则返回值无意义func (u unionFind50) getRelativeDistance(from, to int) int {	u.find(from)	u.find(to)	// to-from = (x-from) - (x-to) = dis[from] - dis[to]	return u.dis[from] - u.dis[to]} // 合并 from 和 to,新增信息 to - from = value// 其中 to 和 from 表示未知量,下文的 x 和 y 也表示未知量// 如果 from 和 to 不在同一个集合,返回 true,否则返回是否与已知信息矛盾func (u unionFind50) merge(from, to int, value int) bool {	x, y := u.find(from), u.find(to)	if x == y { // from 和 to 在同一个集合,不做合并		// to-from = (x-from) - (x-to) = dis[from] - dis[to] = value		return u.dis[from]-u.dis[to] == value	}	//    x --------- y	//   /           /	// from ------- to	// 已知 x-from = dis[from] 和 y-to = dis[to],现在合并 from 和 to,新增信息 to-from = value	// 由于 y-from = (y-x) + (x-from) = (y-to) + (to-from)	// 所以 y-x = (to-from) + (y-to) - (x-from) = value + dis[to] - dis[from]	u.dis[x] = value + u.dis[to] - u.dis[from] // 计算 x 到其代表元 y 的距离	u.fa[x] = y	return true} func cf1850H(in io.Reader, out io.Writer) {	var T, n, m, a, b, d int	for Fscan(in, &T); T > 0; T-- {		Fscan(in, &n, &m)		uf := newUnionFind50(n + 1)		ok := true		for range m {			Fscan(in, &a, &b, &d)			ok = ok && uf.merge(b, a, d)		}		if ok {			Fprintln(out, "YES")		} else {			Fprintln(out, "NO")		}	}} //func main() { cf1850H(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 ↗