- 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
- 108 lines of Go from the credited upstream file 706C.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 . "container/heap"6 . "fmt"7 "io"8)9 10type hPair706C struct {11 x int6412 y int13}14type pairHeap706C []hPair706C15 16func (h pairHeap706C) Len() int { return len(h) }17func (h pairHeap706C) Less(i, j int) bool {18 return h[i].x < h[j].x || h[i].x == h[j].x && h[i].y < h[j].y19}20func (h pairHeap706C) Swap(i, j int) { h[i], h[j] = h[j], h[i] }21func (h *pairHeap706C) Push(v interface{}) { *h = append(*h, v.(hPair706C)) }22func (h *pairHeap706C) Pop() (v interface{}) { n := len(*h); *h, v = (*h)[:n-1], (*h)[n-1]; return }23 2425func Sol706C(reader io.Reader, writer io.Writer) {26 const inf int64 = 1e1827 reverse := func(ss string) string {28 n := len(ss)29 s := make([]byte, n)30 for i := range s {31 s[i] = ss[n-1-i]32 }33 return string(s)34 }35 in := bufio.NewReader(reader)36 out := bufio.NewWriter(writer)37 defer out.Flush()38 39 var n int40 Fscan(in, &n)41 costs := make([]int, n)42 for i := range costs {43 Fscan(in, &costs[i])44 }45 type neighbor struct {46 vertex int47 weight int48 }49 g := make([][]neighbor, 2*n+2)50 var prev, rPrev, cur, rCur string51 for i, c := range costs {52 Fscan(in, &cur)53 rCur = reverse(cur)54 if prev == "" {55 g[0] = []neighbor{{1, 0}, {2, c}}56 } else {57 if prev <= cur {58 g[2*i-1] = append(g[2*i-1], neighbor{2*i + 1, 0})59 }60 if prev <= rCur {61 g[2*i-1] = append(g[2*i-1], neighbor{2*i + 2, c})62 }63 if rPrev <= cur {64 g[2*i] = append(g[2*i], neighbor{2*i + 1, 0})65 }66 if rPrev <= rCur {67 g[2*i] = append(g[2*i], neighbor{2*i + 2, c})68 }69 }70 prev, rPrev = cur, rCur71 }72 g[2*n-1] = []neighbor{{2*n + 1, 0}}73 g[2*n] = []neighbor{{2*n + 1, 0}}74 75 dist := make([]int64, 2*n+2)76 for i := range dist {77 dist[i] = inf78 }79 dist[0] = 080 visited := make([]bool, 2*n+2)81 h := &pairHeap706C{}82 Push(h, hPair706C{0, 0})83 for h.Len() > 0 {84 p := Pop(h).(hPair706C)85 v := p.y86 if visited[v] {87 continue88 }89 visited[v] = true90 for _, e := range g[v] {91 w := e.vertex92 if newDist := dist[v] + int64(e.weight); newDist < dist[w] {93 dist[w] = newDist94 Push(h, hPair706C{newDist, w})95 }96 }97 }98 ans := dist[2*n+1]99 if ans == inf {100 ans = -1101 }102 Fprintln(out, ans)103}104 105106107108