Problem solution · Go

Codeforces 2096E — Wonderful Teddy Bears

Codeforces 2096E — Wonderful Teddy Bears: 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
34 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 2096E — Wonderful Teddy Bears, 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

  • 34 lines of Go from the credited upstream file 2096E.go.
  • The implementation keeps its working state in language-native values and containers.
  • 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 2096E — Wonderful Teddy Bears · GoGo
Use this to learn the idea, then write your own version.
package main import (	. "fmt"	"io") // https://github.com/EndlessChengfunc cf2096E(in io.Reader, out io.Writer) {	var T, n int	var s string	for Fscan(in, &T); T > 0; T-- {		Fscan(in, &n, &s)		var inv, d, r int		for _, c := range s {			if c == 'P' {				r++				continue			}			inv += r			if d%2 != r%2 {				d++			} else if d > 0 {				d--			}		}		// 每两个无法配对的 B 可共用 1 次最小收益操作(消除 1 个逆序对),最后剩余的 1 个 B 需要 1 次最小收益操作(再消除 1 个)		d = (d + 1) / 2		Fprintln(out, (inv+d)/2)	}} //func main() { cf2096E(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 ↗