- 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
- 70 lines of Go from the credited upstream file 1468J.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 9func cf1468J(in io.Reader, out io.Writer) {10 var T, n, m, k int11 for Fscan(in, &T); T > 0; T-- {12 Fscan(in, &n, &m, &k)13 fa := make([]int, n+1)14 for i := range fa {15 fa[i] = i16 }17 find := func(x int) int {18 rt := x19 for fa[rt] != rt {20 rt = fa[rt]21 }22 for fa[x] != rt {23 fa[x], x = rt, fa[x]24 }25 return rt26 }27 cc := n28 29 type edge struct{ v, w, wt int }30 es := []edge{}31 mx := 032 for ; m > 0; m-- {33 var v, w, wt int34 Fscan(in, &v, &w, &wt)35 if wt > k {36 es = append(es, edge{v, w, wt})37 continue38 }39 mx = max(mx, wt)40 v = find(v)41 w = find(w)42 if v != w {43 cc--44 fa[v] = w45 }46 }47 slices.SortFunc(es, func(a, b edge) int { return a.wt - b.wt })48 49 if cc == 1 {50 ans := k - mx51 if len(es) > 0 {52 ans = min(ans, es[0].wt-k)53 }54 Fprintln(out, ans)55 } else {56 sum := 057 for _, e := range es {58 v, w := find(e.v), find(e.w)59 if v != w {60 fa[v] = w61 sum += e.wt - k62 }63 }64 Fprintln(out, sum)65 }66 }67}68 6970