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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
#include<cstdio>
#include<algorithm>
using namespace std;

const int MX = 2001;
struct _p
{
    int i, j, k;
    _p() : i(0), j(0), k(0) {}
    _p(int _i, int _j, int _k) : i(_i), j(_j), k(_k) {}
} p[MX*MX];
bool operator<(const _p &p1, const _p &p2) { return p1.k < p2.k; }
int pn = 0;
int vi[MX], vj[MX];

int main()
{
    int n;
    scanf("%d", &n);
    for (int i=0; i<n; i++)
        for (int j=0; j<n-i; j++)
        {
            int k;
            scanf("%d", &k);
            p[pn++] = _p(i, j+i, k);
        }
    sort(p, p+pn);
    for (int i=0; i<n; i++) vi[i] = vj[i] = -1;
    int u = 0;
    long long w = 0;
    for (int k=0; k<pn && u<n; k++)
    {
        _p &r = p[k];
        if (vj[r.i] != r.j/* && vi[r.j] != r.i*/)
        {
            u++;
            w += r.k;

            int ri = r.i, rj = r.j;
            while (vj[ri] != -1)
            {
                if (vj[ri] > rj)
                {
                    vi[vj[ri]] = rj+1;
                    
                    int t = vj[ri];
                    vj[ri] = rj+1;
                    
                    ri = rj+1;
                    rj = t;
                }
                else
                {
                    ri = vj[ri]+1;
                }
            }
            vj[ri] = rj;
            
            rj = r.j;
            ri = vi[rj];
            
            while (vi[rj] != -1)
            {
                if (vi[rj] < ri)
                {
                    vj[vi[rj]] = ri-1;

                    int t = vi[rj];
                    vi[rj] = ri-1;

                    rj = ri-1;
                    ri = t;
                }
                else
                {
                    rj = vi[rj]-1;
                }
            }
            vi[rj] = ri;
        }
    }
    printf("%lld\n", w);
    return 0;
}