- 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
- 62 lines of Go from the credited upstream file 1156D.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)8 910func Sol1156D(reader io.Reader, writer io.Writer) {11 var find func([]int, int) int12 find = func(fa []int, i int) int {13 if fa[i] != i {14 fa[i] = find(fa, fa[i])15 }16 return fa[i]17 }18 merge := func(fa []int, size []int, from, to int) {19 from, to = find(fa, from), find(fa, to)20 if from != to {21 fa[from] = to22 size[to] += size[from]23 }24 }25 26 in := bufio.NewReader(reader)27 out := bufio.NewWriter(writer)28 defer out.Flush()29 30 var n int31 Fscan(in, &n)32 fa := [2][]int{}33 size := [2][]int{}34 for i := range fa {35 fa[i] = make([]int, n)36 for j := range fa[i] {37 fa[i][j] = j38 }39 size[i] = make([]int, n)40 for j := range size[i] {41 size[i][j] = 142 }43 }44 for m := n - 1; m > 0; m-- {45 var v, w, c int46 Fscan(in, &v, &w, &c)47 merge(fa[c], size[c], v-1, w-1)48 }49 50 ans := int64(0)51 for i := range fa[0] {52 53 54 ans += int64(size[0][find(fa[0], i)])*int64(size[1][find(fa[1], i)]) - 155 }56 Fprint(out, ans)57}58 59606162