- 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
- 67 lines of Go from the credited upstream file 1081D.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 "bufio"5 . "fmt"6 "io"7 "sort"8 "strconv"9 "strings"10)11 1213func CF1081D(_r io.Reader, _w io.Writer) {14 in := bufio.NewReader(_r)15 var n, m, k, v int16 Fscan(in, &n, &m, &k)17 sp := make([]bool, n)18 for i := 0; i < k; i++ {19 Fscan(in, &v)20 sp[v-1] = true21 }22 es := make([][3]int, m)23 for i := range es {24 Fscan(in, &es[i][0], &es[i][1], &es[i][2])25 }26 sort.Slice(es, func(i, j int) bool { return es[i][2] < es[j][2] })27 28 fa := make([]int, n)29 for i := range fa {30 fa[i] = i31 }32 var find func(int) int33 find = func(x int) int {34 if fa[x] != x {35 fa[x] = find(fa[x])36 }37 return fa[x]38 }39 cnt := 140 merge := func(x, y int) {41 x, y = find(x), find(y)42 if x == y {43 return44 }45 if sp[x] && sp[y] {46 cnt++47 fa[y] = x48 } else if sp[x] {49 fa[y] = x50 } else {51 fa[x] = y52 }53 }54 for i := 0; ; {55 w := es[i][2]56 for ; i < m && es[i][2] == w; i++ {57 merge(es[i][0]-1, es[i][1]-1)58 }59 if cnt == k {60 Fprint(_w, strings.Repeat(strconv.Itoa(w)+" ", k))61 break62 }63 }64}65 6667