- 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
- 110 lines of Go from the credited upstream file 1442C.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)8 910type deque42 struct{ l, r []int }11 12func (q deque42) empty() bool { return len(q.l) == 0 && len(q.r) == 0 }13func (q *deque42) pushL(v int) { q.l = append(q.l, v) }14func (q *deque42) pushR(v int) { q.r = append(q.r, v) }15func (q *deque42) popL() (v int) {16 if len(q.l) > 0 {17 q.l, v = q.l[:len(q.l)-1], q.l[len(q.l)-1]18 } else {19 v, q.r = q.r[0], q.r[1:]20 }21 return22}23 24func CF1442C(_r io.Reader, out io.Writer) {25 in := bufio.NewReader(_r)26 const mod = 99824435327 pow := func(x int64, n int) (res int64) {28 res = 129 for ; n > 0; n >>= 1 {30 if n&1 > 0 {31 res = res * x % mod32 }33 x = x * x % mod34 }35 return36 }37 38 var n, m, v, w int39 Fscan(in, &n, &m)40 type nb struct{ to, wt int }41 g := make([][]nb, n+1)42 for ; m > 0; m-- {43 Fscan(in, &v, &w)44 g[v] = append(g[v], nb{w, 0})45 g[w] = append(g[w], nb{v, 1})46 }47 48 minTr := make([]int, n+1)49 for i := range minTr {50 minTr[i] = 1e951 }52 minTr[1] = 053 q := &deque42{}54 q.pushL(1)55 for !q.empty() {56 v := q.popL()57 for _, e := range g[v] {58 w, d := e.to, minTr[v]&1^e.wt 59 if newD := minTr[v] + d; newD < minTr[w] {60 minTr[w] = newD61 if d == 0 {62 q.pushL(w)63 } else {64 q.pushR(w)65 }66 }67 }68 }69 70 dis := make([][20]int, n+1)71 for i := range dis {72 for j := range dis[i] {73 dis[i][j] = 1e974 }75 }76 dis[1][0] = 077 type pair struct{ v, lv int }78 q2 := []pair{{1, 0}}79 for len(q2) > 0 {80 p := q2[0]81 q2 = q2[1:]82 v := p.v83 for _, e := range g[v] {84 w, wt := e.to, p.lv&1^e.wt 85 86 if lv := p.lv + wt - minTr[w]; lv < 20 {87 if newD := dis[v][p.lv-minTr[v]] + 1; newD < dis[w][lv] {88 dis[w][lv] = newD89 q2 = append(q2, pair{w, p.lv + wt})90 }91 }92 }93 }94 95 minT, minD := int(1e9), 096 for i, d := range dis[n] {97 98 if t := i + minTr[n]; minT > 19 || t > 19 {99 if t < minT {100 minT, minD = t, d101 }102 } else if 1<<t+d < 1<<minT+minD {103 minT, minD = t, d104 }105 }106 Fprint(out, (int64(minD)+pow(2, minT)-1)%mod)107}108 109110