Problem solution · Go

Codeforces 1494C — 1D Sokoban

Codeforces 1494C — 1D Sokoban: 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
76 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 1494C — 1D Sokoban, 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

  • 76 lines of Go from the credited upstream file 1494C.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 1494C — 1D Sokoban · GoGo
Use this to learn the idea, then write your own version.
package main import (	"bufio"	. "fmt"	"io"	"sort") // https://space.bilibili.com/206214func CF1494C(_r io.Reader, _w io.Writer) {	in := bufio.NewReader(_r)	out := bufio.NewWriter(_w)	defer out.Flush()	max := func(a, b int) int {		if b > a {			return b		}		return a	} 	var T, n, m int	for Fscan(in, &T); T > 0; T-- {		Fscan(in, &n, &m)		a := make([]int, n)		for i := range a {			Fscan(in, &a[i])		}		b := make([]int, m)		for i := range b {			Fscan(in, &b[i])		}		f := func(a, b []int) int {			same, i, n := 0, 0, len(a)			for _, v := range b {				for i < n && a[i] < v {					i++				}				if i < n && a[i] == v {					same++					i++				}			}			res := same			i, left := 0, 0			for right, v := range b {				for i < n && a[i] < v {					i++				}				if i < n && a[i] == v {					same--					i++				}				for left <= right && v-b[left]+1 > i { // b[left] 到 b[right] 的特殊位置无法被 i 个连续箱子覆盖					left++				}				res = max(res, right-left+1+same)			}			return res		}		x, y := sort.SearchInts(a, 0), sort.SearchInts(b, 0)		ans := f(a[x:], b[y:])		// 负数变正数且递增,方便复用 f		for i := 0; i < (x+1)/2; i++ {			a[i], a[x-1-i] = -a[x-1-i], -a[i]		}		for i := 0; i < (y+1)/2; i++ {			b[i], b[y-1-i] = -b[y-1-i], -b[i]		}		ans += f(a[:x], b[:y])		Fprintln(out, ans)	}} //func main() { CF1494C(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 ↗