Pretty damn straight forward recursive call problem with prefix sum…

AC Code

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
#include <algorithm>
#include <cassert>
#include <climits>
#include <cstdio>
#include <map>
#include <vector>

using namespace std;

typedef long long int ll;

vector<ll> pre;
ll solve(int l, int r, int depth, int k, int inp[], int n)
{
    if (r - l < 3) {
        return 0;
    }

    // printf("%d %d\n", l, r);
    if (depth == k) {
        return 0;
    }

    ll mn = LLONG_MAX;
    int who = -1;
    ll left = inp[l];
    ll right = 0;
    for (int i = l + 2; i < r; i++) {
        right += 1LL * inp[i] * (i - (l + 1)); // watch out for the 1LL conversion
    }

    for (int i = l + 1; i < r - 1; i++) { // left and right bound can not be used
        ll tmp = abs(abs(right) - abs(left));
        if (tmp < mn) {
            mn = tmp;
            who = i;
        }

        left += inp[i];
        left += pre[i - 1] - pre[l - 1]; // this l - 1 cost me 3 hours...

        right -= pre[r - 1] - pre[i]; // watch out for the condition
    }

    ll idx = inp[who] + solve(l, who, depth + 1, k, inp, n) +
             solve(who + 1, r, depth + 1, k, inp, n);

    return idx;
}

int main()
{
    int n, k;
    scanf("%d %d", &n, &k);

    int inp[n + 1];
    for (int i = 0; i < n; i++)
        scanf("%d", &inp[i + 1]);

    pre.push_back(0);
    for (int i = 0; i < n; i++) {
        pre.push_back(pre[i] + inp[i + 1]);
    }

    ll ret = solve(1, n + 1, 0, k, inp, n);

    printf("%lld\n", ret);

    return 0;
}