- Translate each rule into one explicit state update.
- Maintain the invariant after every processed item.
- Return the accumulated state once all relevant input has been handled.
Code notes
- 67 lines of Go from the credited upstream file 339E.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.
Use this to learn the idea, then write your own version.
1package main2 3import (4 "bufio"5 . "fmt"6 "io"7 "slices"8)9 1011func cf339E(_r io.Reader, out io.Writer) {12 in := bufio.NewReader(_r)13 abs := func(x int) int {14 if x < 0 {15 return -x16 }17 return x18 }19 var n int20 Fscan(in, &n)21 a := make([]int, n+2)22 a[0] = -123 for i := 1; i <= n; i++ {24 Fscan(in, &a[i])25 }26 a[n+1] = -127 28 ans := [3][2]int{}29 var f func(int) bool30 f = func(k int) bool {31 for i := 1; i <= n; i++ {32 if a[i] != i {33 goto next34 }35 }36 Fprintln(out, 2-k)37 for _, p := range ans[k+1:] {38 Fprintln(out, p[0], p[1])39 }40 return true41 next:42 if k < 0 {43 return false44 }45 for i := 1; i <= n; i++ {46 if a[i] == i || abs(a[i]-a[i-1]) == 1 && abs(a[i]-a[i+1]) == 1 {47 continue48 }49 for j := i + 1; j <= n; j++ {50 if a[j] == j || abs(a[j]-a[j-1]) == 1 && abs(a[j]-a[j+1]) == 1 {51 continue52 }53 slices.Reverse(a[i : j+1])54 ans[k] = [2]int{i, j}55 if f(k - 1) {56 return true57 }58 slices.Reverse(a[i : j+1])59 }60 }61 return false62 }63 f(2)64}65 6667