- 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
- 85 lines of Go from the credited upstream file 1242C.go.
- The implementation visibly relies on sequence storage.
- 1 loop block 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 CF1242C(_r io.Reader, out io.Writer) {11 in := bufio.NewReader(_r)12 var n, m int13 Fscan(in, &n)14 a := make([][]int64, n)15 id := map[int64]int{}16 sum := make([]int64, n)17 tot := int64(0)18 for i := range a {19 Fscan(in, &m)20 a[i] = make([]int64, m)21 for j := range a[i] {22 Fscan(in, &a[i][j])23 id[a[i][j]] = i + 124 sum[i] += a[i][j]25 }26 tot += sum[i]27 }28 if tot%int64(n) != 0 {29 Fprint(out, "No")30 return31 }32 tot /= int64(n)33 34 pick := make([]int64, n)35 to := make([]int, n)36 vis := make([]bool, 1<<n)37 var f func(int, int) bool38 f = func(s, p int) bool {39 if p == n {40 return true41 }42 if vis[s] {43 return false44 }45 if s>>p&1 > 0 {46 return f(s, p+1)47 }48 s |= 1 << p49 o:50 for _, v := range a[p] {51 pick[p] = v52 t, q, cur := s, p, v53 for {54 w := tot - sum[q] + cur55 if w == v {56 to[p] = q + 157 break58 }59 q = id[w] - 160 if q < 0 || t>>q&1 > 0 {61 continue o62 }63 pick[q], to[q] = w, id[cur]64 t |= 1 << q65 cur = w66 }67 if f(t, p+1) {68 return true69 }70 vis[t] = true71 }72 return false73 }74 if f(0, 0) {75 Fprintln(out, "Yes")76 for i, v := range pick {77 Fprintln(out, v, to[i])78 }79 } else {80 Fprint(out, "No")81 }82}83 8485