Problem solution · Go

Codeforces 1503D — Flip the Cards

Codeforces 1503D — Flip the Cards: a Go solution using sorting and greedy selection. Learn the idea, check the complexity, and read the full code, with credit to EndlessCheng Codeforces Go.

Technique
Sorting and greedy selection
Source
EndlessCheng Codeforces Go
Length
82 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

Sorting and greedy selection

For Codeforces 1503D — Flip the Cards, the implementation first exposes a useful order, then scans that order while making locally justified choices.

  1. Choose the key that reveals the greedy or grouping structure.
  2. Sort the relevant records by that key.
  3. Scan in order, maintaining the invariant that makes each local choice safe.

Code notes

  • 82 lines of Go from the credited upstream file 1503D.go.
  • The implementation visibly relies on sequence storage.
  • No explicit loop blocks detected.

Complexity

Sorting is typically the dominant term unless the subsequent scan uses a more expensive nested operation.

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 1503D — Flip the Cards · GoGo
Use this to learn the idea, then write your own version.
package main import (	. "fmt"	"io"	"slices") func cf1503D(in io.Reader, out io.Writer) {	var n, x, y, ans int	Fscan(in, &n)	to := make([]int, n*2+1)	pos := make([]byte, n*2+1)	for i := 0; i < n; i++ {		Fscan(in, &x, &y)		pos[y] = 1		to[x] = y		to[y] = x	} 	a := make([]int, n)	al, ar := 0, n-1	b := make([]int, n)	bl, br := 0, n-1	vis := make([]bool, n*2+2)	mn, mx := 1, n*2	for mn < mx {		cnt := [2]int{}		t := mn		for t > 0 {			last := 0			for ; mn <= t; mn++ {				if vis[mn] {					continue				}				cnt[pos[mn]]++ 				vis[mn] = true				a[al] = mn				al++ 				last = to[mn]				vis[last] = true				b[bl] = last				bl++			}			if last == 0 {				break			} 			t = last			last = 0			for ; mx >= t; mx-- {				if vis[mx] {					continue				}				cnt[pos[mx]]++ 				vis[mx] = true				a[ar] = mx				ar-- 				last = to[mx]				vis[last] = true				b[br] = last				br--			}			t = last		}		ans += min(cnt[0], cnt[1])	} 	slices.Reverse(b)	if !slices.IsSorted(a) || !slices.IsSorted(b) {		Fprint(out, -1)	} else {		Fprint(out, ans)	}} //func main() { cf1503D(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 ↗