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
#include <iostream>

#define INF 2000000000

using namespace std;

int n, t, m;
long long int ret = 0;

int tab[2000][2000];

int cost[2000];

int main() {

    cin >> n;
    for (int i = 0; i < n; ++i) {

        cost[i] = INF;

        for (int j = 0; j < n - i; ++j)
            cin >> tab[i][j];
    }

    cost[n - 1] = tab[n - 1][0];

    for (int k = n - 2; k >= 0; --k) {

        // Check intervals.
        for (int j = 0; j < n - k; ++j) {

            int this_cost = tab[k][j];

            // Check if this interval offers any gain.
            // This could be done in log time instead of linear.
            int gain = 0;
            bool found_better = false;
            int ind;
            for (int l = k; l <= k + j; ++l) {
       
                if (cost[l] - this_cost > gain) {
                    gain = cost[l] - this_cost;
                    ind = l;
                    found_better = true;
                }
            }
            
            if (found_better)
                cost[ind] = this_cost;
        }
    }

    long long int ret = 0;
    for (int i = 0; i < n; ++i)
        ret += cost[i];

    // for (int i = 0; i < n; ++i) {
    //     cout << cost[i] << " ";
    // }
    // cout << "\n";

    cout << ret << "\n";

    return 0;
}