Problem solution · Go

Codeforces 888G — Xor-MST

Codeforces 888G — Xor-MST: a Go solution using direct simulation. Learn the idea, check the complexity, and read the full code, with credit to EndlessCheng Codeforces Go.

Technique
Direct simulation
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

Direct simulation

For Codeforces 888G — Xor-MST, the implementation follows the problem’s operations directly while maintaining only the state needed for the next decision.

  1. Translate each rule into one explicit state update.
  2. Maintain the invariant after every processed item.
  3. Return the accumulated state once all relevant input has been handled.

Code notes

  • 79 lines of Go from the credited upstream file 888G.go.
  • The implementation visibly relies on sequence storage.
  • No explicit loop blocks detected.

Complexity

Count the number and nesting of passes over the input, then include the maintained containers in the memory estimate.

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 888G — Xor-MST · GoGo
Use this to learn the idea, then write your own version.
package main import (	"bufio"	. "fmt"	"io"	"math") // https://space.bilibili.com/206214type node88 struct{ son [2]*node88 }type trie88 struct{ root *node88 } const trieBitLen88 = 30 func (t *trie88) put(v int32) *node88 {	o := t.root	for i := trieBitLen88 - 1; i >= 0; i-- {		b := v >> i & 1		if o.son[b] == nil {			o.son[b] = &node88{}		}		o = o.son[b]	}	return o} func (t *trie88) minXor(v int32) (ans int) {	o := t.root	for i := trieBitLen88 - 1; i >= 0; i-- {		b := v >> i & 1		if o.son[b] == nil {			ans |= 1 << i			b ^= 1		}		o = o.son[b]	}	return} func CF888G(_r io.Reader, out io.Writer) {	in := bufio.NewReader(_r)	var n, ans int	Fscan(in, &n)	a := make([]int32, n)	for i := range a {		Fscan(in, &a[i])	} 	var f func([]int32, int)	f = func(a []int32, p int) {		if a == nil || p < 0 {			return		}		b := [2][]int32{}		for _, v := range a {			k := v >> p & 1			b[k] = append(b[k], v)		}		if b[0] != nil && b[1] != nil {			t := &trie88{&node88{}}			for _, v := range b[0] {				t.put(v)			}			res := math.MaxInt			for _, v := range b[1] {				res = min(res, t.minXor(v))			}			ans += res		}		f(b[0], p-1)		f(b[1], p-1)	}	f(a, 29)	Fprint(out, ans)} //func main() { CF888G(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 ↗