Problem solution · Go

Codeforces 1999F — Expected Median

Codeforces 1999F — Expected Median: 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
84 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 1999F — Expected Median, 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

  • 84 lines of Go from the credited upstream file 1999F.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 1999F — Expected Median · GoGo
Use this to learn the idea, then write your own version.
package main import (	. "fmt"	"io"	"slices") // https://github.com/EndlessChengconst mod99 = 1_000_000_007 func pow99(x, n int) (res int) {	res = 1	for ; n > 0; n /= 2 {		if n%2 > 0 {			res = res * x % mod99		}		x = x * x % mod99	}	return} type comb99 struct{ _f, _invF []int } func newComb99(mx int) *comb99 {	c := &comb99{[]int{1}, []int{1}}	c._grow(mx)	return c} func (c *comb99) _grow(mx int) {	n := len(c._f)	c._f = slices.Grow(c._f, mx+1)[:mx+1]	for i := n; i <= mx; i++ {		c._f[i] = c._f[i-1] * i % mod99	}	c._invF = slices.Grow(c._invF, mx+1)[:mx+1]	c._invF[mx] = pow99(c._f[mx], mod99-2)	for i := mx; i > n; i-- {		c._invF[i-1] = c._invF[i] * i % mod99	}} func (c *comb99) f(n int) int {	if n >= len(c._f) {		c._grow(n * 2)	}	return c._f[n]} func (c *comb99) invF(n int) int {	if n >= len(c._f) {		c._grow(n * 2)	}	return c._invF[n]} func (c *comb99) c(n, k int) int {	if k < 0 || k > n {		return 0	}	return c.f(n) * c.invF(k) % mod99 * c.invF(n-k) % mod99} func cf1999F(in io.Reader, out io.Writer) {	cm := newComb99(0)	var T, n, k, v int	for Fscan(in, &T); T > 0; T-- {		Fscan(in, &n, &k)		c1 := 0		for range n {			Fscan(in, &v)			c1 += v		}		ans := 0		for i := range k/2 + 1 {			ans = (ans + cm.c(n-c1, i)*cm.c(c1, k-i)) % mod99		}		Fprintln(out, ans)	}} //func main() { cf1999F(bufio.NewReader(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 ↗