Pivot Splitting (APCS 2018-02 Advanced)
2.0s 256MEach entry is a positive weight at a unit-spaced position. Split an interval \([l,r]\) at an interior pivot \(p\) minimizing \(|\sum_{i=l}^r(i-p)a_i|\), choosing the leftmost on ties. Remove the pivot and recursively split both sides. The first split has depth \(1\); stop beyond depth \(K\) or with fewer than three entries. Sum the removed weights.
Input
Read \(n,K\), then the \(n\) weights.
Constraints
\(1\le n\le50000\), \(0\le K<30\), \(a_i\ge1\), \(\sum a_i\le10^9\).
Output
Print the sum of removed weights.
Sample Input 1
7 1
2 4 1 3 7 6 9
Sample Output 1
7
Sample Input 2
7 3
2 4 1 3 7 6 9
Sample Output 2
11
Source
Log in to write and submit code.
Log in