Problem solution · Go

Codeforces 498E — Stairs and Lines

Codeforces 498E — Stairs and Lines: a Go solution using sliding window or two pointers. Learn the idea, check the complexity, and read the full code, with credit to EndlessCheng Codeforces Go.

Technique
Sliding window or two pointers
Source
EndlessCheng Codeforces Go
Length
75 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

Sliding window or two pointers

For Codeforces 498E — Stairs and Lines, the implementation maintains a moving interval and updates only the information that enters or leaves the window.

  1. Choose the invariant that makes a window valid or useful.
  2. Advance the right boundary and add the new element.
  3. Move the left boundary only as needed while maintaining the invariant and updating the answer.

Code notes

  • 75 lines of Go from the credited upstream file 498E.go.
  • The implementation visibly relies on sequence storage.
  • No explicit loop blocks detected.

Complexity

Confirm that neither pointer moves backwards; if so, the scan is usually linear apart from the window’s data-structure operations.

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 498E — Stairs and Lines · GoGo
Use this to learn the idea, then write your own version.
package main import (	. "fmt"	"io") // https://github.com/EndlessChengtype matrix98 [][]int func newMatrix98(n, m int) matrix98 {	a := make(matrix98, n)	for i := range a {		a[i] = make([]int, m)	}	return a} func (a matrix98) mul(b matrix98) matrix98 {	c := newMatrix98(len(a), len(b[0]))	for i, row := range a {		for k, x := range row {			if x == 0 {				continue			}			for j, y := range b[k] {				c[i][j] = (c[i][j] + x*y) % 1_000_000_007			}		}	}	return c} func (a matrix98) powMul(n int, f0 matrix98) matrix98 {	res := f0	for ; n > 0; n /= 2 {		if n%2 > 0 {			res = a.mul(res)		}		a = a.mul(a)	}	return res} func cf498E(in io.Reader, out io.Writer) {	var w int	f := matrix98{{1}}	for h := 1; h <= 7; h++ {		m := newMatrix98(1<<h, 1<<h)		for right := range m {			for left := range m[right] {				f0, f1 := 0, 1				for i := range h {					s := f0 + f1					if left&right>>i&1 > 0 {						f1 = f0					} else {						f1 = s					}					f0 = s				}				m[right][left] = f1			}		} 		Fscan(in, &w)		// 在 f 的前面插入一堆 {0},旧的状态就自动相当于高位是 1 了		f = append(newMatrix98(len(f), 1), f...)		f = m.powMul(w, f)	}	Fprint(out, f[1<<7-1][0])} //func main() { cf498E(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 ↗