- 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 859E.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 CF859E(_r io.Reader, out io.Writer) {11 in := bufio.NewReader(_r)12 const mod int64 = 1e9 + 713 14 var m, v, w int15 Fscan(in, &m)16 n := 2 * m17 fa := make([]int, n)18 for i := range fa {19 fa[i] = i20 }21 var find func(int) int22 find = func(x int) int {23 if fa[x] != x {24 fa[x] = find(fa[x])25 }26 return fa[x]27 }28 sl := make([]bool, n)29 c := make([]bool, n)30 sz := make([]int, n)31 for i := range sz {32 sz[i] = 133 }34 for ; m > 0; m-- {35 Fscan(in, &v, &w)36 v--37 w--38 if v == w {39 sl[v] = true40 continue41 }42 v, w = find(v), find(w)43 if v == w {44 c[v] = true45 continue46 }47 fa[v] = w48 sz[w] += sz[v]49 if sl[v] {50 sl[w] = true51 }52 }53 ans := int64(1)54 for i, b := range sl {55 if !b && i == find(i) {56 if c[i] {57 ans = ans * 2 % mod58 } else {59 ans = ans * int64(sz[i]) % mod60 }61 }62 }63 Fprint(out, ans)64}65 6667