- 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
- 99 lines of Go from the credited upstream file 144D.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 hPair144 struct{ x, y int }11type pairHeap144 []hPair14412 13func (h pairHeap144) Len() int { return len(h) }14func (h pairHeap144) Less(i, j int) bool { return h[i].x < h[j].x || h[i].x == h[j].x && h[i].y < h[j].y }15func (h pairHeap144) Swap(i, j int) { h[i], h[j] = h[j], h[i] }16func (h *pairHeap144) Push(v interface{}) { *h = append(*h, v.(hPair144)) }17func (h *pairHeap144) Pop() (v interface{}) { n := len(*h); *h, v = (*h)[:n-1], (*h)[n-1]; return }18 1920func Sol144D(reader io.Reader, writer io.Writer) {21 in := bufio.NewScanner(reader)22 in.Split(bufio.ScanWords)23 out := bufio.NewWriter(writer)24 defer out.Flush()25 read := func() (x int) {26 in.Scan()27 for _, b := range in.Bytes() {28 x = x*10 + int(b-'0')29 }30 return31 }32 33 n, m, st := read(), read(), read()-134 type neighbor struct{ to, weight int }35 g := make([][]neighbor, n)36 for i := 0; i < m; i++ {37 v, w, weight := read()-1, read()-1, read()38 g[v] = append(g[v], neighbor{w, weight})39 g[w] = append(g[w], neighbor{v, weight})40 }41 l := read()42 43 const inf int = 1e9 + 144 dist := make([]int, n)45 for i := range dist {46 dist[i] = inf47 }48 dist[st] = 049 h := &pairHeap144{}50 Push(h, hPair144{0, st})51 for h.Len() > 0 {52 p := Pop(h).(hPair144)53 d, v := p.x, p.y54 if dist[v] < d {55 continue56 }57 for _, e := range g[v] {58 w := e.to59 if newD := dist[v] + e.weight; newD < dist[w] {60 dist[w] = newD61 Push(h, hPair144{newD, w})62 }63 }64 }65 66 ans := 067 for _, d := range dist {68 if d == l {69 ans++70 }71 }72 for v, edges := range g {73 for _, e := range edges {74 w := e.to75 if w < v {76 continue77 }78 dv, dw, size := dist[v], dist[w], e.weight79 80 posv := l - dv81 posw := size - (l - dw)82 if posv > posw {83 continue84 }85 if 0 < posv && posv < size {86 ans++87 }88 if 0 < posw && posw < size && posw != posv {89 ans++90 }91 }92 }93 Fprint(out, ans)94}95 96979899