- 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
- 60 lines of Go from the credited upstream file 1774D.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 cf1774D(in io.Reader, _w io.Writer) {11 out := bufio.NewWriter(_w)12 defer out.Flush()13 var T, n, m int14 for Fscan(in, &T); T > 0; T-- {15 Fscan(in, &n, &m)16 a := make([][]int, n)17 cnt := make([]int, n)18 s := 019 for i := range a {20 a[i] = make([]int, m)21 for j := range a[i] {22 Fscan(in, &a[i][j])23 if a[i][j] > 0 {24 cnt[i]++25 s++26 }27 }28 }29 if s%n > 0 {30 Fprintln(out, -1)31 continue32 }33 34 ans := [][3]int{}35 avg := s / n36 for j := range m {37 var ins, outs []int38 for i, c := range cnt {39 if c < avg && a[i][j] == 0 {40 ins = append(ins, i)41 } else if c > avg && a[i][j] > 0 {42 outs = append(outs, i)43 }44 }45 for i := range min(len(ins), len(outs)) {46 ans = append(ans, [3]int{ins[i] + 1, outs[i] + 1, j + 1})47 cnt[ins[i]]++48 cnt[outs[i]]--49 }50 }51 52 Fprintln(out, len(ans))53 for _, p := range ans {54 Fprintln(out, p[0], p[1], p[2])55 }56 }57}58 5960