Approach
Sorting and greedy selection
For Codeforces 2043C — Sums on Segments, the implementation first exposes a useful order, then scans that order while making locally justified choices.
- Choose the key that reveals the greedy or grouping structure.
- Sort the relevant records by that key.
- Scan in order, maintaining the invariant that makes each local choice safe.
Code notes
- 71 lines of Go from the credited upstream file 2043C.go.
- The implementation visibly relies on sequence storage.
- No explicit loop blocks detected.
Complexity
Sorting is typically the dominant term unless the subsequent scan uses a more expensive nested operation.
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 "slices"8)9 1011func dp43(a []int) (minF, maxF int) {12 f, g := 0, 013 for _, v := range a {14 f = min(f, 0) + v15 g = max(g, 0) + v16 minF = min(minF, f)17 maxF = max(maxF, g)18 }19 return20}21 22func cf2043C(in io.Reader, _w io.Writer) {23 out := bufio.NewWriter(_w)24 defer out.Flush()25 var T, n int26 for Fscan(in, &T); T > 0; T-- {27 Fscan(in, &n)28 a := make([]int, n)29 idx := 030 for i := range a {31 Fscan(in, &a[i])32 if a[i] < -1 || a[i] > 1 {33 idx = i34 }35 }36 37 ans := []int{}38 add := func(l, r int) {39 for i := l; i <= r; i++ {40 ans = append(ans, i)41 }42 }43 44 add(dp43(a[:idx]))45 add(dp43(a[idx+1:]))46 var l, minL, maxL int47 for i := idx - 1; i >= 0; i-- {48 l += a[i]49 minL = min(minL, l)50 maxL = max(maxL, l)51 }52 var r, minR, maxR int53 for _, v := range a[idx+1:] {54 r += v55 minR = min(minR, r)56 maxR = max(maxR, r)57 }58 add(minL+a[idx]+minR, maxL+a[idx]+maxR)59 slices.Sort(ans)60 ans = slices.Compact(ans)61 62 Fprintln(out, len(ans))63 for _, v := range ans {64 Fprint(out, v, " ")65 }66 Fprintln(out)67 }68}69 7071