- 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
- 117 lines of Go from the credited upstream file 1461F.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 CF1461F(_r io.Reader, _w io.Writer) {12 in := bufio.NewReader(_r)13 out := bufio.NewWriter(_w)14 defer out.Flush()15 output := func(a []byte, op string) {16 Fprint(out, a[0])17 for _, v := range a[1:] {18 Fprint(out, op, v)19 }20 }21 22 var n, st int23 Fscan(in, &n)24 a := make([]byte, n)25 for i := range a {26 Fscan(in, &a[i])27 }28 var s string29 Fscan(in, &s)30 if s == "+-" || s == "-+" {31 s = "+"32 }33 34 if len(s) == 1 {35 output(a, s)36 return37 }38 39 if s == "*-" || s == "-*" {40 posZ := bytes.IndexByte(a, 0)41 if posZ <= 0 {42 output(a, "*")43 } else {44 output(a[:posZ], "*")45 Fprint(out, "-")46 output(a[posZ:], "*")47 }48 return49 }50 51 pos := []int{} 52 a = append(a, 0) 53 54 for i, v := range a {55 if v > 1 {56 pos = append(pos, i)57 continue58 }59 if v == 1 {60 if len(pos) == 0 { 61 if i > 0 {62 Fprint(out, "+")63 }64 Fprint(out, 1)65 }66 continue67 }68 if m := len(pos); m > 0 {69 addPos := 070 71 if m < 20 && 1<<m <= 9*(i-st) {72 max := int64(0)73 for sub := 0; sub < 1<<(m-1); sub++ {74 sum, mul := int64(0), int64(a[pos[0]])75 for i := 1; i < m; i++ {76 if sub>>(i-1)&1 > 0 {77 sum += mul + int64(pos[i]-pos[i-1]-1)78 mul = int64(a[pos[i]])79 } else {80 mul *= int64(a[pos[i]])81 }82 if sum+mul > max {83 max, addPos = sum+mul, sub84 }85 }86 }87 }88 if pos[0] > 0 {89 Fprint(out, "+")90 }91 Fprint(out, a[pos[0]])92 for i := 1; i < m; i++ {93 op := "*"94 if addPos>>(i-1)&1 > 0 {95 op = "+"96 }97 for _, v := range a[pos[i-1]+1 : pos[i]+1] {98 Fprint(out, op, v)99 }100 }101 for _, v := range a[pos[m-1]+1 : i] {102 Fprint(out, "+", v)103 }104 }105 if i < n {106 if i > 0 {107 Fprint(out, "+")108 }109 Fprint(out, 0)110 }111 pos = nil112 st = i + 1113 }114}115 116117