Problem solution · Go

Codeforces 785D — Anton and School - 2

Codeforces 785D — Anton and School - 2: 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
56 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 785D — Anton and School - 2, 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

  • 56 lines of Go from the credited upstream file 785D.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 785D — Anton and School - 2 · GoGo
Use this to learn the idea, then write your own version.
package main import (	"bufio"	. "fmt"	"io"	"strings") // github.com/EndlessCheng/codeforces-gofunc CF785D(in io.Reader, out io.Writer) {	const mod int64 = 1e9 + 7	pow := func(x, n int64) (res int64) {		res = 1		for ; n > 0; n >>= 1 {			if n&1 > 0 {				res = res * x % mod			}			x = x * x % mod		}		return res	} 	var s string	Fscan(bufio.NewReader(in), &s)	n := len(s)	F := make([]int64, n+1)	F[0] = 1	for i := 1; i <= n; i++ {		F[i] = F[i-1] * int64(i) % mod	}	invF := make([]int64, n+1)	invF[n] = pow(F[n], mod-2)	for i := n; i > 0; i-- {		invF[i-1] = invF[i] * int64(i) % mod	}	C := func(n, k int) int64 { return F[n] * invF[k] % mod * invF[n-k] % mod } 	ans := int64(0)	l, r := 0, strings.Count(s, ")")	for _, b := range s {		if r == 0 {			break		}		if b == '(' { // ∑ 左边 i-1 个括号,右边 i 个括号			l++			ans = (ans + C(l+r-1, l)) % mod		} else {			r--		}	}	Fprint(out, ans)} //func main() { CF785D(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 ↗