Problem solution · Go

Codeforces 840C — On the Bench

Codeforces 840C — On the Bench: 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
65 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 840C — On the Bench, 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

  • 65 lines of Go from the credited upstream file 840C.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 840C — On the Bench · GoGo
Use this to learn the idea, then write your own version.
package main import (	. "fmt"	"io") // https://github.com/EndlessChengfunc cf840C(in io.Reader, out io.Writer) {	const M = 1_000_000_007	const mx = 301	C := [mx][mx]int{}	for i := range C {		C[i][0] = 1		for j := 1; j <= i; j++ {			C[i][j] = (C[i-1][j-1] + C[i-1][j]) % M		}	} 	var n, v, s int	Fscan(in, &n)	cnt := map[int]int{}	perm := 1	for range n {		Fscan(in, &v)		for j := 2; j*j <= v; j++ {			for v%(j*j) == 0 {				v /= j * j			}		}		cnt[v]++		perm = perm * cnt[v] % M	} 	f := make([][]int, n+1)	for i := range f {		f[i] = make([]int, n+1)	}	f[0][0] = perm 	i := 0	for _, c := range cnt {		// 一共有 s+1 个空隙,其中有 bad 个坏空隙,s+1-bad 个好空隙		for bad, dp := range f[i][:s+1] {			if dp == 0 {				continue			}			for b := 1; b <= c; b++ {				for j := range min(bad, b) + 1 {					// 把这 c 个数分成 b 块,方案数为 C[c-1][b-1]					// 选择其中的 j 块插到坏空隙中,方案数为 C[bad][j]					// 剩下的 b-j 块插到好空隙中,方案数为 C[s+1-bad][b-j]					// 坏空隙减少了 j,增加了 c-b					f[i+1][bad-j+c-b] = (f[i+1][bad-j+c-b] + dp*C[c-1][b-1]%M*C[bad][j]%M*C[s+1-bad][b-j]) % M				}			}		}		i++		s += c	}	Fprint(out, f[i][0])} //func main() { cf840C(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 ↗