- 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
- 106 lines of Go from the credited upstream file 1340C.go.
- The implementation visibly relies on sequence storage, work queue.
- 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 "sort"8)9 1011type pair40 struct{ i, t int }12type deque40 struct{ l, r []pair40 }13 14func (q deque40) empty() bool { return len(q.l) == 0 && len(q.r) == 0 }15func (q *deque40) pushL(v pair40) { q.l = append(q.l, v) }16func (q *deque40) pushR(v pair40) { q.r = append(q.r, v) }17func (q *deque40) popL() (v pair40) {18 if len(q.l) > 0 {19 q.l, v = q.l[:len(q.l)-1], q.l[len(q.l)-1]20 } else {21 v, q.r = q.r[0], q.r[1:]22 }23 return24}25 26func CF1340C(_r io.Reader, out io.Writer) {27 in := bufio.NewReader(_r)28 min := func(a, b int64) int64 {29 if a > b {30 return b31 }32 return a33 }34 35 var n, m, g, r int36 Fscan(in, &n, &m)37 x := make([]int, m)38 for i := range x {39 Fscan(in, &x[i])40 }41 sort.Ints(x)42 Fscan(in, &g, &r)43 for i := 1; i < m; i++ {44 if x[i]-x[i-1] > g {45 Fprint(out, -1)46 return47 }48 }49 50 dis := make([][]int, m)51 for i := range dis {52 dis[i] = make([]int, g+1)53 for j := range dis[i] {54 dis[i][j] = 1e955 }56 }57 dis[0][g] = 058 q := &deque40{}59 q.pushL(pair40{0, g})60 for !q.empty() {61 p := q.popL()62 i, t := p.i, p.t63 d := dis[i][t]64 if t > 0 {65 if i > 0 {66 if j := t - (x[i] - x[i-1]); j >= 0 && d < dis[i-1][j] {67 dis[i-1][j] = d68 q.pushL(pair40{i - 1, j})69 }70 }71 if i < m-1 {72 if j := t - (x[i+1] - x[i]); j >= 0 && d < dis[i+1][j] {73 dis[i+1][j] = d74 q.pushL(pair40{i + 1, j})75 }76 }77 } else {78 newD := d + 179 if i > 0 {80 if j := g - (x[i] - x[i-1]); newD < dis[i-1][j] {81 dis[i-1][j] = newD82 q.pushR(pair40{i - 1, j})83 }84 }85 if i < m-1 {86 if j := g - (x[i+1] - x[i]); newD < dis[i+1][j] {87 dis[i+1][j] = newD88 q.pushR(pair40{i + 1, j})89 }90 }91 }92 }93 ans := int64(1e18)94 for j, d := range dis[m-1] {95 if d < 1e9 {96 ans = min(ans, int64(d)*int64(r+g)+int64(g-j))97 }98 }99 if ans == 1e18 {100 ans = -1101 }102 Fprint(out, ans)103}104 105106