- 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
- 68 lines of Go from the credited upstream file 1896F.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 "bytes"6 . "fmt"7 "io"8)9 1011func cf1896F(in io.Reader, _w io.Writer) {12 out := bufio.NewWriter(_w)13 defer out.Flush()14 var T, n int15 var s []byte16 for Fscan(in, &T); T > 0; T-- {17 Fscan(in, &n, &s)18 m := n * 219 if s[0] != s[m-1] || bytes.Count(s, []byte{'1'})%2 > 0 {20 Fprintln(out, -1)21 continue22 }23 24 if s[0]&1 > 0 {25 Fprintln(out, 3)26 Fprint(out, "(")27 for i := n - 2; i >= 0; i-- {28 Fprint(out, "()")29 }30 Fprintln(out, ")")31 Fprint(out, "(")32 s[0] ^= 133 s[m-1] ^= 134 } else {35 Fprintln(out, 2)36 Fprint(out, "(")37 }38 39 c := 040 for i := 1; i < m-1; i += 2 {41 if s[i] != s[i+1] {42 c ^= 143 s[i+c] ^= 144 if c > 0 {45 Fprint(out, "((")46 } else {47 Fprint(out, "))")48 }49 } else {50 Fprint(out, "()")51 }52 }53 Fprintln(out, ")")54 55 Fprint(out, "(")56 for i := 1; i < m-1; i += 2 {57 if s[i]&1 > 0 {58 Fprint(out, ")(")59 } else {60 Fprint(out, "()")61 }62 }63 Fprintln(out, ")")64 }65}66 6768