- 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
- 54 lines of Go from the credited upstream file 2117G.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 . "fmt"5 "io"6 "slices"7)8 910func cf2117G(in io.Reader, out io.Writer) {11 var T, n, m int12 for Fscan(in, &T); T > 0; T-- {13 Fscan(in, &n, &m)14 type edge struct{ v, w, wt int }15 es := make([]edge, m)16 for i := range es {17 Fscan(in, &es[i].v, &es[i].w, &es[i].wt)18 }19 slices.SortFunc(es, func(a, b edge) int { return a.wt - b.wt })20 21 fa := make([]int, n+1)22 mn := make([]int, n+1)23 for i := range fa {24 fa[i] = i25 mn[i] = 1e926 }27 find := func(x int) int {28 rt := x29 for fa[rt] != rt {30 rt = fa[rt]31 }32 for fa[x] != rt {33 fa[x], x = rt, fa[x]34 }35 return rt36 }37 ans := int(2e9)38 for _, e := range es {39 v, w := find(e.v), find(e.w)40 if v == w {41 continue42 }43 mn[w] = min(mn[w], mn[v], e.wt)44 fa[v] = w45 if find(1) == find(n) {46 ans = min(ans, mn[fa[1]]+e.wt)47 }48 }49 Fprintln(out, ans)50 }51}52 5354