- 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
- 71 lines of Go from the credited upstream file 82D.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 . "fmt"5 "io"6 "slices"7)8 910func cf82D(in io.Reader, out io.Writer) {11 var n int12 Fscan(in, &n)13 a := make([]int, n)14 for i := range a {15 Fscan(in, &a[i])16 }17 18 fr := make([][]int, n)19 for i := range fr {20 fr[i] = make([]int, n)21 }22 var f []int23 if n%2 > 0 {24 f = slices.Clone(a)25 } else {26 f = make([]int, n)27 for i, x := range a {28 f[i] = max(x, a[n-1])29 }30 }31 for i := n - 3 + n%2; i > 0; i -= 2 {32 b, c := a[i], a[i+1]33 for j, a := range a[:i] {34 r1 := f[j] + max(b, c)35 r2 := f[i] + max(a, c)36 r3 := f[i+1] + max(a, b)37 fr[i][j] = j38 if r2 < r1 {39 fr[i][j] = i40 r1 = r241 }42 if r3 < r1 {43 fr[i][j] = i + 144 r1 = r345 }46 f[j] = r147 }48 }49 Fprintln(out, f[0])50 51 j := 052 for i := 1; i < n-2+n%2; i += 2 {53 j2 := fr[i][j]54 if j2 == j {55 Fprintln(out, i+1, i+2)56 } else if j2 == i {57 Fprintln(out, j+1, i+2)58 } else {59 Fprintln(out, j+1, i+1)60 }61 j = j262 }63 if n%2 > 0 {64 Fprintln(out, j+1)65 } else {66 Fprintln(out, j+1, n)67 }68}69 7071