- 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
- 102 lines of Go from the credited upstream file 1715E.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 "math/big"9)10 1112type vec15 struct{ x, y int }13 14func (a vec15) sub(b vec15) vec15 { return vec15{a.x - b.x, a.y - b.y} }15func (a vec15) dot(b vec15) int { return a.x*b.x + a.y*b.y }16func (a vec15) detCmp(b vec15) int {17 v := new(big.Int).Mul(big.NewInt(int64(a.x)), big.NewInt(int64(b.y)))18 w := new(big.Int).Mul(big.NewInt(int64(a.y)), big.NewInt(int64(b.x)))19 return v.Cmp(w)20}21 22func cf1715E(in io.Reader, _w io.Writer) {23 out := bufio.NewWriter(_w)24 defer out.Flush()25 var n, m, k int26 Fscan(in, &n, &m, &k)27 type nb struct{ to, wt int }28 g := make([][]nb, n)29 for range m {30 var v, w, wt int31 Fscan(in, &v, &w, &wt)32 v--33 w--34 g[v] = append(g[v], nb{w, wt})35 g[w] = append(g[w], nb{v, wt})36 }37 38 dis := make([]int, n)39 for i := range dis {40 dis[i] = 1e1841 }42 dis[0] = 043 dij := func() []int {44 h := make(hp15, n)45 for i, d := range dis {46 h[i] = pair15{d, i}47 }48 heap.Init(&h)49 for len(h) > 0 {50 p := heap.Pop(&h).(pair15)51 v := p.v52 d := p.dis53 if d > dis[v] {54 continue55 }56 for _, e := range g[v] {57 w := e.to58 newD := d + e.wt59 if newD < dis[w] {60 dis[w] = newD61 heap.Push(&h, pair15{newD, w})62 }63 }64 }65 return dis66 }67 68 for range k {69 dij()70 q := []vec15{}71 for i, d := range dis {72 v := vec15{i, i*i + d}73 for len(q) > 1 && q[len(q)-1].sub(q[len(q)-2]).detCmp(v.sub(q[len(q)-1])) <= 0 {74 q = q[:len(q)-1]75 }76 q = append(q, v)77 }78 for i := range dis {79 p := vec15{-2 * i, 1}80 for len(q) > 1 && p.dot(q[0]) >= p.dot(q[1]) {81 q = q[1:]82 }83 dis[i] = p.dot(q[0]) + i*i84 }85 }86 dij()87 88 for _, v := range dis {89 Fprint(out, v, " ")90 }91}92 9394 95type pair15 struct{ dis, v int }96type hp15 []pair1597func (h hp15) Len() int { return len(h) }98func (h hp15) Less(i, j int) bool { return h[i].dis < h[j].dis }99func (h hp15) Swap(i, j int) { h[i], h[j] = h[j], h[i] }100func (h *hp15) Push(v any) { *h = append(*h, v.(pair15)) }101func (h *hp15) Pop() (v any) { a := *h; *h, v = a[:len(a)-1], a[len(a)-1]; return }102