- 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 1487C.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 CF1487C(_r io.Reader, _w io.Writer) {11 in := bufio.NewReader(_r)12 out := bufio.NewWriter(_w)13 defer out.Flush()14 type nb struct{ to, i int }15 16 var T, n int17 for Fscan(in, &T); T > 0; T-- {18 Fscan(in, &n)19 g := make([][]nb, n)20 m := 021 for i := 0; i < n; i++ {22 j := i + 123 if n&1 == 0 && i&1 == 0 {24 j++25 m++26 }27 for ; j < n; j++ {28 g[i] = append(g[i], nb{j, m})29 g[j] = append(g[j], nb{i, m})30 m++31 }32 }33 34 ans := make([]int, m)35 vis := make([]bool, m)36 pre := 037 var f func(int)38 f = func(v int) {39 for len(g[v]) > 0 {40 e := g[v][0]41 g[v] = g[v][1:]42 if w, i := e.to, e.i; !vis[i] {43 vis[i] = true44 f(w)45 v := v46 if w == pre {47 v, w = w, v48 }49 if v < w {50 ans[i] = 151 } else {52 ans[i] = -153 }54 pre = w55 }56 }57 }58 f(0)59 for _, v := range ans {60 Fprint(out, v, " ")61 }62 Fprintln(out)63 }64}65 6667