Problem solution · Go

Codeforces 1147D — Palindrome XOR

Codeforces 1147D — Palindrome XOR: 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
79 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 1147D — Palindrome XOR, 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

  • 79 lines of Go from the credited upstream file 1147D.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 1147D — Palindrome XOR · GoGo
Use this to learn the idea, then write your own version.
package main import (	. "fmt"	"io") // https://github.com/EndlessChengtype uf47 struct {	fa, dis []int	cc      int} func newUnionFind47(n int) uf47 {	fa := make([]int, n)	dis := make([]int, n)	for i := range fa {		fa[i] = i	}	return uf47{fa, dis, n}} func (u uf47) find(x int) int {	if u.fa[x] != x {		root := u.find(u.fa[x])		u.dis[x] ^= u.dis[u.fa[x]]		u.fa[x] = root	}	return u.fa[x]} func (u *uf47) merge(from, to, value int) bool {	x, y := u.find(from), u.find(to)	if x == y {		return u.dis[from]^u.dis[to] == value	}	u.dis[x] = value ^ u.dis[to] ^ u.dis[from]	u.fa[x] = y	u.cc--	return true} func cf1147D(in io.Reader, out io.Writer) {	const mod = 998244353	s := ""	Fscan(in, &s)	n := len(s)	ans := 0o:	for st := 1; st < n; st++ {		u := newUnionFind47(n * 2)		for i := range n / 2 {			u.merge(i, n-1-i, 0)		}		for i := 1; i < st; i++ {			if s[i] != '?' && !u.merge(i, 0, int('1'-s[i])) {				break o			}		}		u.merge(n+st, 0, 0)		for i, j := st, n-1; i < j; i, j = i+1, j-1 {			u.merge(n+i, n+j, 0)		}		for i := st; i < n; i++ {			if s[i] != '?' && !u.merge(i, n+i, int(s[i]-'0')) {				continue o			}		}		m := 1		for range u.cc - st - 1 {			m = m * 2 % mod		}		ans += m	}	Fprint(out, ans%mod)} //func main() { cf1147D(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 ↗