- 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 196E.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 "container/heap"5 . "fmt"6 "io"7 "slices"8)9 1011func cf196E(in io.Reader, out io.Writer) {12 var n, m, k, v, w, wt int13 Fscan(in, &n, &m)14 type nb struct{ to, wt int }15 g := make([][]nb, n)16 type edge struct{ v, w, wt int }17 es := make([]edge, m)18 for i := range m {19 Fscan(in, &v, &w, &wt)20 v--21 w--22 g[v] = append(g[v], nb{w, wt})23 g[w] = append(g[w], nb{v, wt})24 es[i] = edge{v, w, wt}25 }26 27 dis := make([]int, n)28 from := make([]int, n)29 for i := range dis {30 dis[i] = 1e1831 from[i] = i32 }33 Fscan(in, &k)34 h := make(hp96, k)35 for i := range k {36 Fscan(in, &v)37 v--38 dis[v] = 039 h[i].v = v40 }41 for len(h) > 0 {42 p := heap.Pop(&h).(pair96)43 v := p.v44 d := p.d45 if d > dis[v] {46 continue47 }48 for _, e := range g[v] {49 w := e.to50 newD := d + e.wt51 if newD < dis[w] {52 dis[w] = newD53 from[w] = from[v] 54 heap.Push(&h, pair96{newD, w})55 }56 }57 }58 59 ans := dis[0]60 for i, e := range es {61 es[i].wt += dis[e.v] + dis[e.w]62 }63 slices.SortFunc(es, func(a, b edge) int { return a.wt - b.wt })64 65 fa := dis66 for i := range fa {67 fa[i] = i68 }69 find := func(x int) int {70 rt := x71 for fa[rt] != rt {72 rt = fa[rt]73 }74 for fa[x] != rt {75 fa[x], x = rt, fa[x]76 }77 return rt78 }79 80 for _, e := range es {81 v := find(from[e.v])82 w := find(from[e.w])83 if v != w {84 ans += e.wt85 fa[v] = w86 }87 }88 Fprint(out, ans)89}90 9192type pair96 struct{ d, v int }93type hp96 []pair9694func (h hp96) Len() int { return len(h) }95func (h hp96) Less(i, j int) bool { return h[i].d < h[j].d }96func (h hp96) Swap(i, j int) { h[i], h[j] = h[j], h[i] }97func (h *hp96) Push(v any) { *h = append(*h, v.(pair96)) }98func (h *hp96) Pop() (v any) { a := *h; *h, v = a[:len(a)-1], a[len(a)-1]; return }99