- 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
- 81 lines of Go from the credited upstream file 1559D2.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 910type uf59 []int11 12func (u uf59) find(x int) int {13 if u[x] != x {14 u[x] = u.find(u[x])15 }16 return u[x]17}18 19func (u uf59) merge(from, to int) bool {20 x, y := u.find(from), u.find(to)21 if x == y {22 return false23 }24 u[x] = y25 return true26}27 28func (u uf59) same(x, y int) bool {29 return u.find(x) == u.find(y)30}31 32func cf1559D2(in io.Reader, _w io.Writer) {33 out := bufio.NewWriter(_w)34 defer out.Flush()35 var n, m1, m2 int36 Fscan(in, &n, &m1, &m2)37 init := func(m int) uf59 {38 u := make(uf59, n+1)39 for i := range u {40 u[i] = i41 }42 for range m {43 var v, w int44 Fscan(in, &v, &w)45 u.merge(v, w)46 }47 return u48 }49 u1 := init(m1)50 u2 := init(m2)51 52 ans := [][2]int{}53 for i := 1; i <= n; i++ {54 if !u1.same(i, 1) && !u2.same(i, 1) {55 ans = append(ans, [2]int{i, 1})56 u1.merge(i, 1)57 u2.merge(i, 1)58 }59 }60 61 var a, b []int62 for i := 1; i <= n; i++ {63 if u1.merge(i, 1) {64 a = append(a, i)65 }66 if u2.merge(i, 1) {67 b = append(b, i)68 }69 }70 for i := range min(len(a), len(b)) {71 ans = append(ans, [2]int{a[i], b[i]})72 }73 74 Fprintln(out, len(ans))75 for _, p := range ans {76 Fprintln(out, p[0], p[1])77 }78}79 8081