- 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
- 71 lines of Go from the credited upstream file 101341A.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 _013412 3import (4 "bufio"5 . "fmt"6 "io"7 "sort"8)9 1011func CF101341A(_r io.Reader, _w io.Writer) {12 in := bufio.NewReader(_r)13 out := bufio.NewWriter(_w)14 defer out.Flush()15 type pair struct{ x, y, i int }16 17 var n, d int18 var s []byte19 var ls, rs []pair20 Fscan(in, &n)21 for i := 1; i <= n; i++ {22 Fscan(in, &s)23 l, r := 0, 024 for _, b := range s {25 if b == '(' {26 l++27 } else if l > 0 {28 l--29 } else {30 r++31 }32 }33 if r < l {34 ls = append(ls, pair{r, l, i})35 } else {36 rs = append(rs, pair{l, r, i})37 }38 d += l - r39 }40 41 sort.Slice(ls, func(i, j int) bool { return ls[i].x < ls[j].x })42 sort.Slice(rs, func(i, j int) bool { return rs[i].x < rs[j].x })43 f := func(ps []pair) []int {44 ans := []int{}45 s := 046 for _, p := range ps {47 if s < p.x {48 return nil49 }50 s += p.y - p.x51 ans = append(ans, p.i)52 }53 return ans54 }55 ansL := f(ls)56 ansR := f(rs)57 if d == 0 && ansL != nil && ansR != nil {58 Fprintln(out, "YES")59 for _, v := range ansL {60 Fprint(out, v, " ")61 }62 for i := len(ansR) - 1; i >= 0; i-- {63 Fprint(out, ansR[i], " ")64 }65 } else {66 Fprint(out, "NO")67 }68}69 7071