- 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
- 80 lines of Go from the credited upstream file 1406B.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 . "fmt"5 "io"6 "slices"7)8 910func cf1406B(in io.Reader, out io.Writer) {11 abs := func(x int) int {12 if x < 0 {13 return -x14 }15 return x16 }17 const k = 518 var T, n int19 for Fscan(in, &T); T > 0; T-- {20 Fscan(in, &n)21 a := make([]int, n)22 for i := range a {23 Fscan(in, &a[i])24 }25 26 slices.SortFunc(a, func(a, b int) int { return abs(b) - abs(a) })27 if a[k-1] == 0 {28 Fprintln(out, 0)29 continue30 }31 32 var neg, posL, negL, posR, negR int33 mul := 134 for _, v := range a[:k] {35 if v < 0 {36 v = -v37 neg++38 negL = v39 } else {40 posL = v41 }42 mul = mul * v43 }44 if neg%2 == 0 {45 Fprintln(out, mul)46 continue47 }48 49 ans := mul50 for _, v := range a[k:] {51 if v > 0 {52 posR = v53 break54 }55 }56 for _, v := range a[k:] {57 if v < 0 {58 negR = -v59 break60 }61 }62 if (posL == 0 || negR == 0) && posR > 0 || posL*posR > negL*negR {63 ans = mul / negL * posR64 } else if posL > 0 && negR > 0 {65 ans = mul / posL * negR66 } else if a[n-1] == 0 {67 ans = 068 } else {69 ans = 170 for _, v := range a[n-k:] {71 ans = ans * abs(v)72 }73 ans = -ans74 }75 Fprintln(out, ans)76 }77}78 7980