- 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 1290C.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 cf1290C(in io.Reader, _w io.Writer) {11 out := bufio.NewWriter(_w)12 defer out.Flush()13 var n, k, m, v, ans int14 var s string15 Fscan(in, &n, &k, &s)16 idx := make([][]int, n)17 fa := make([]int, k+1)18 sz := make([][2]int, k+1)19 sz[0][0] = 1e9 20 for i := 1; i <= k; i++ {21 Fscan(in, &m)22 for range m {23 Fscan(in, &v)24 idx[v-1] = append(idx[v-1], i)25 }26 fa[i] = i27 28 sz[i][0] = 129 }30 31 dis := make([]byte, k+1)32 var find func(int) int33 find = func(x int) int {34 if fa[x] != x {35 f := find(fa[x])36 dis[x] ^= dis[fa[x]]37 fa[x] = f38 }39 return fa[x]40 }41 minOp := func(x int) int { return min(sz[x][0], sz[x][1]) }42 43 for i, p := range idx {44 if p == nil {45 Fprintln(out, ans)46 continue47 }48 from, to := p[0], 049 if len(p) > 1 {50 to = p[1]51 }52 x, y := find(from), find(to)53 if x != y {54 d := s[i]&1 ^ 1 ^ dis[from] ^ dis[to]55 dis[x] = d56 fa[x] = y57 ans -= minOp(x) + minOp(y)58 sz[y][0] += sz[x][d]59 sz[y][1] += sz[x][d^1]60 ans += minOp(y)61 }62 Fprintln(out, ans)63 }64}65 6667