Approach
Sorting and greedy selection
For Codeforces 2021E3 — Digital Village (Extreme Version), the implementation first exposes a useful order, then scans that order while making locally justified choices.
- Choose the key that reveals the greedy or grouping structure.
- Sort the relevant records by that key.
- Scan in order, maintaining the invariant that makes each local choice safe.
Code notes
- 81 lines of Go from the credited upstream file 2021E3.go.
- The implementation visibly relies on sequence storage.
- No explicit loop blocks detected.
Complexity
Sorting is typically the dominant term unless the subsequent scan uses a more expensive nested operation.
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 . "fmt"6 "io"7 "slices"8)9 1011func cf2021E3(in io.Reader, _w io.Writer) {12 out := bufio.NewWriter(_w)13 defer out.Flush()14 var T, n, m, p int15 for Fscan(in, &T); T > 0; T-- {16 Fscan(in, &n, &m, &p)17 cnt := make([]int, n)18 for range p {19 var v int20 Fscan(in, &v)21 v--22 cnt[v] = 123 }24 type edge struct{ wt, u, v int }25 es := make([]edge, m)26 for i := range es {27 var u, v, w int28 Fscan(in, &u, &v, &w)29 es[i] = edge{w, u - 1, v - 1}30 }31 slices.SortFunc(es, func(a, b edge) int { return a.wt - b.wt })32 33 fa := make([]int, n)34 for i := range n {35 fa[i] = i36 }37 var find func(int) int38 find = func(x int) int {39 if fa[x] != x {40 fa[x] = find(fa[x])41 }42 return fa[x]43 }44 45 ws := make([]int, n)46 d := make([]int, 0, p-1)47 for _, e := range es {48 u := find(e.u)49 v := find(e.v)50 if u == v {51 continue52 }53 if cnt[u] < cnt[v] {54 u, v = v, u55 }56 fa[v] = u57 if cnt[v] == 0 {58 continue59 }60 cu := cnt[u]61 cv := cnt[v]62 cnt[u] += cnt[v]63 nw := min(ws[u]+e.wt*cv, ws[v]+e.wt*cu)64 d = append(d, ws[u]+ws[v]-nw)65 ws[u] = nw66 }67 68 s := ws[find(0)]69 slices.Sort(d)70 for i := range n {71 Fprint(out, s, " ")72 if i < len(d) {73 s += d[i]74 }75 }76 Fprintln(out)77 }78}79 8081