Problem solution · Go

Codeforces 1288E — Messenger Simulator

Codeforces 1288E — Messenger Simulator: 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
57 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 1288E — Messenger Simulator, 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

  • 57 lines of Go from the credited upstream file 1288E.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 1288E — Messenger Simulator · GoGo
Use this to learn the idea, then write your own version.
package main import (	"bufio"	. "fmt"	"io") // https://github.com/EndlessChengtype fenwick88 []int func (f fenwick88) update(i, val int) {	for i++; i < len(f); i += i & -i {		f[i] += val	}} func (f fenwick88) pre(i int) (res int) {	for ; i > 0; i &= i - 1 {		res += f[i]	}	return} func cf1288E(in io.Reader, _w io.Writer) {	out := bufio.NewWriter(_w)	defer out.Flush()	var n, m, v int	Fscan(in, &n, &m)	mn := make([]int, n)	mx := make([]int, n)	pos := make([]int, n)	t := make(fenwick88, m+n+1)	for i := range mn {		mn[i] = i		pos[i] = m + i		t.update(m+i, 1)	} 	for i := m - 1; i >= 0; i-- {		Fscan(in, &v)		v--		mn[v] = 0		old := pos[v]		pos[v] = i		mx[v] = max(mx[v], t.pre(old)) // 在移动前达到最大		t.update(old, -1)		t.update(i, 1)	} 	for i, v := range mn {		Fprintln(out, v+1, max(mx[i], t.pre(pos[i]))+1)	}} //func main() { cf1288E(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 ↗