- 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
- 82 lines of Go from the credited upstream file 1646F.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 cf1646F(in io.Reader, _w io.Writer) {11 out := bufio.NewWriter(_w)12 defer out.Flush()13 var n, tot int14 Fscan(in, &n)15 a := make([][]int, n+1)16 for i := range a {17 a[i] = make([]int, n+1)18 }19 for i := 1; i <= n; i++ {20 for j := 1; j <= n; j++ {21 var x int22 Fscan(in, &x)23 a[i][x]++24 }25 }26 27 op := make([][]int, n*n)28 for i := range op {29 op[i] = make([]int, n+1)30 }31 32 calc := func(x, y int) {33 tot++34 for {35 for i := 1; i <= n; i++ {36 if a[x][i] > 1 {37 op[tot-1][x] = i38 a[x][i]--39 a[x%n+1][i]++40 break41 }42 }43 x = x%n + 144 if x == y {45 break46 }47 }48 }49 50 var f func()51 f = func() {52 for i := 1; i <= n; i++ {53 for j := 1; j <= n; j++ {54 if a[i][j] > 1 {55 calc(i, i)56 f()57 return58 }59 }60 }61 }62 f()63 64 Fprintln(out, tot+(n*n-n)/2)65 for i := range tot {66 for j := 1; j <= n; j++ {67 Fprint(out, op[i][j], " ")68 }69 Fprintln(out)70 }71 for i := 2; i <= n; i++ {72 for j := i; j >= 2; j-- {73 for k := 1; k <= n; k++ {74 Fprint(out, (j+k-2)%n+1, " ")75 }76 Fprintln(out)77 }78 }79}80 8182