Approach
Sorting and greedy selection
For Codeforces 1667B — Optimal Partition, 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
- 72 lines of Go from the credited upstream file 1667B.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 "sort"9)10 1112type fenwick67 []int13 14func newFenwickTree67(n int) fenwick67 {15 t := make(fenwick67, n+1)16 for i := range t {17 t[i] = -1e1818 }19 return t20}21 22func (f fenwick67) update(i, v int) {23 for ; i < len(f); i += i & -i {24 f[i] = max(f[i], v)25 }26}27 28func (f fenwick67) pre(i int) int {29 res := int(-1e18)30 for ; i > 0; i &= i - 1 {31 res = max(res, f[i])32 }33 return res34}35 36func cf1667B(in io.Reader, _w io.Writer) {37 out := bufio.NewWriter(_w)38 defer out.Flush()39 var T, n int40 for Fscan(in, &T); T > 0; T-- {41 Fscan(in, &n)42 s := make([]int, n+1)43 for i := 1; i <= n; i++ {44 Fscan(in, &s[i])45 s[i] += s[i-1]46 }47 48 sorted := slices.Clone(s)49 slices.Sort(sorted)50 sorted = slices.Compact(sorted)51 m := len(sorted)52 53 lessT := newFenwickTree67(m)54 grT := newFenwickTree67(m)55 maxF := newFenwickTree67(m)56 57 f := 058 for r, v := range s {59 v = sort.SearchInts(sorted, v)60 if r > 0 {61 f = max(lessT.pre(v)+r, grT.pre(m-1-v)-r, maxF[v])62 }63 lessT.update(v+1, f-r)64 grT.update(m-v, f+r)65 maxF[v] = max(maxF[v], f)66 }67 Fprintln(out, f)68 }69}70 7172