- 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
- 134 lines of Go from the credited upstream file 1508C.go.
- The implementation visibly relies on sequence storage.
- 1 loop block 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 . "fmt"6 "io"7 "sort"8)9 1011func prim(g [][]int) (mst int) {12 n := len(g)13 minW := make([]int, n)14 for i := range minW {15 minW[i] = 2e916 }17 minW[0] = 018 used := make([]bool, n)19 for {20 v := -121 for i, u := range used {22 if !u && (v < 0 || minW[i] < minW[v]) {23 v = i24 }25 }26 if v < 0 {27 break28 }29 used[v] = true30 mst += minW[v]31 for w, wt := range g[v] {32 if wt < minW[w] {33 minW[w] = wt34 }35 }36 }37 return38}39 40func CF1508C(_r io.Reader, out io.Writer) {41 in := bufio.NewReader(_r)42 var n, m, xor int43 Fscan(in, &n, &m)44 type edge struct{ v, w, wt int }45 es := make([]edge, m)46 for i := range es {47 var v, w, wt int48 Fscan(in, &v, &w, &wt)49 xor ^= wt50 es[i] = edge{v - 1, w - 1, wt}51 }52 53 54 if m >= (n-2)*(n-1)/2 {55 g := make([][]int, n)56 for i := range g {57 g[i] = make([]int, n)58 }59 for _, e := range es {60 g[e.v][e.w] = e.wt61 g[e.w][e.v] = e.wt62 }63 ans := int(1e18)64 for i, r := range g {65 for j, wt := range r[:i] {66 if wt == 0 { 67 g[i][j] = xor68 g[j][i] = xor69 ans = min(ans, prim(g))70 g[i][j] = 071 g[j][i] = 072 }73 }74 }75 Fprint(out, ans)76 return77 }78 79 80 81 fa := make([]int, n)82 for i := range fa {83 fa[i] = i84 }85 var find func(int) int86 find = func(x int) int {87 if fa[x] != x {88 fa[x] = find(fa[x])89 }90 return fa[x]91 }92 g := make([][]int, n)93 for _, e := range es {94 g[e.v] = append(g[e.v], e.w)95 g[e.w] = append(g[e.w], e.v)96 }97 maxV := 098 for v, ws := range g {99 if len(ws) < len(g[maxV]) {100 maxV = v101 }102 }103 mergeInv := func(v int) {104 has := map[int]bool{v: true}105 for _, w := range g[v] {106 has[w] = true107 }108 for i := range g {109 if !has[i] {110 fa[find(i)] = find(v)111 }112 }113 }114 mergeInv(maxV)115 for v := range g {116 if find(v) != find(maxV) {117 mergeInv(v)118 }119 }120 121 sort.Slice(es, func(i, j int) bool { return es[i].wt < es[j].wt })122 ans := 0123 for _, e := range es {124 v, w := find(e.v), find(e.w)125 if v != w {126 fa[v] = w127 ans += e.wt128 }129 }130 Fprint(out, ans)131}132 133134