Problem solution · Go

Codeforces 464B — Restore Cube

Codeforces 464B — Restore Cube : 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
55 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 464B — Restore Cube , 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

  • 55 lines of Go from the credited upstream file 464B.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 464B — Restore Cube · GoGo
Use this to learn the idea, then write your own version.
package main import (	. "fmt"	"io") // github.com/EndlessCheng/codeforces-gofunc CF464B(in io.Reader, out io.Writer) {	perm3 := [][3]int{{0, 1, 2}, {0, 2, 1}, {1, 0, 2}, {1, 2, 0}, {2, 0, 1}, {2, 1, 0}}	dis := func(p, q [3]int64) int64 { return (p[0]-q[0])*(p[0]-q[0]) + (p[1]-q[1])*(p[1]-q[1]) + (p[2]-q[2])*(p[2]-q[2]) } 	ps := make([][3]int64, 8)	for i := range ps {		Fscan(in, &ps[i][0], &ps[i][1], &ps[i][2])	}	var f func(int, map[int64]int8) bool	f = func(i int, dmp map[int64]int8) bool {		if i == 8 {			return len(dmp) == 3		}		p := ps[i]	o:		for _, m := range perm3 {			mp := map[int64]int8{}			for k, c := range dmp {				mp[k] = c			}			ps[i] = [3]int64{p[m[0]], p[m[1]], p[m[2]]}			for j := 0; j < i; j++ {				d := dis(ps[i], ps[j])				// 剪枝:立方体的性质是距离只有三种且每种个数不超过 12				if mp[d]++; len(mp) > 3 || mp[d] > 12 {					continue o				}			}			if f(i+1, mp) {				return true			}		}		return false	}	// 注意从 1 开始,避免无效运算	if f(1, map[int64]int8{}) {		Fprintln(out, "YES")		for _, p := range ps {			Fprintln(out, p[0], p[1], p[2])		}	} else {		Fprint(out, "NO")	}} //func main() { CF464B(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 ↗