Problem solution · Go

Codeforces 678E — Another Sith Tournament

Codeforces 678E — Another Sith Tournament: 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
46 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 678E — Another Sith Tournament, 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

  • 46 lines of Go from the credited upstream file 678E.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 678E — Another Sith Tournament · GoGo
Use this to learn the idea, then write your own version.
package main import (	"bufio"	. "fmt"	"io"	"math"	"math/bits") // github.com/EndlessCheng/codeforces-gofunc CF678E(_r io.Reader, out io.Writer) {	in := bufio.NewReader(_r)	var n int	Fscan(in, &n)	p := make([][]float64, n)	for i := range p {		p[i] = make([]float64, n)		for j := range p[i] {			Fscan(in, &p[i][j])		}	} 	// 下面将原题中的编号 1 称为编号 0	// f[mask] 表示当前参赛的人为 mask 时,编号 0 获胜的概率(不在 mask 中表示此人已被淘汰)	f := make([]float64, 1<<n)	f[1] = 1 // 只有编号 0,此时编号 0 获胜的概率为 1	for i := 3; i < 1<<n; i += 2 { // 只计算含有编号 0 的集合(即奇数),因为根据定义,f[不含编号 0 的集合] 一定是 0		for s, lb := i, 0; s > 0; s ^= lb {			lb = s & -s			x := bits.TrailingZeros(uint(lb))			for t, lb2 := s^lb, 0; t > 0; t ^= lb2 {				lb2 = t & -t				y := bits.TrailingZeros(uint(lb2))				// 若 x 和 y 均不为 0,那么相当于先让 x 和 y 比,然后胜者后面去和编号 0 比				// 枚举胜者是谁,然后相加				// 也可以从记忆化的角度来理解,循环的过程就是记忆化自底向上的过程				f[i] = math.Max(f[i], f[i^lb]*p[y][x]+f[i^lb2]*p[x][y])			}		}	}	Fprintf(out, "%.8f", f[1<<n-1])} //func main() { CF678E(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 ↗