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
85
#include <cstdio>
#include <climits>
#include <vector>
#include <queue>
#include <algorithm>
using namespace std;

class FU {
    std::vector<int> p;
public:
    FU(int n);
    int f(int x);                   // find
    void u(int x, int y);           // union
    bool s(int x, int y);           // are x and y in the same set?
    int a();                        // add new element as singleton, return id of new element
    int size(int x);                // return number of elements in set containing x
    int operator()(int x);          // alias for f
    bool operator()(int x, int y);  // alias for s
};

FU::FU(int n) : p(n, -1) {}

int FU::f(int x) {
    int t, r = x;
    while (p[r] >= 0)
        r = p[r];
    while (x != r)
        t = p[x],
        p[x] = r,
        x = t;
    return r;
}

void FU::u(int x, int y) {
    x = f(x);
    y = f(y);
    if (x == y)
        return;
    if (p[x] < p[y])
        p[x] += p[y], p[y] = x;
    else
        p[y] += p[x], p[x] = y;
}

bool FU::s(int x, int y) { return f(x) == f(y); }

int FU::a() { p.push_back(-1); return p.size() - 1; }

int FU::size(int x) { return -p[f(x)]; }

int FU::operator()(int x) { return f(x); }

bool FU::operator()(int x, int y) { return s(x, y); }



#define mp make_pair

typedef long long ll;

int read() { int n; scanf("%d", &n); return n; }

int main() {
    int n = read();
    priority_queue<pair<int,pair<int,int> > > q;
    for (int a=0; a<n; ++a)
        for (int b=a; b<n; ++b)
            q.push(mp(-read(), mp(a, b)));
    FU fu(n+1);
    ll res = 0;
    while (!q.empty()) {
        pair<int,pair<int,int> > p = q.top();
        q.pop();
        int k = -p.first;
        int a = p.second.first;
        int b = p.second.second;
        if (fu(a, b+1))
            continue;
        res += k;
        fu.u(a, b+1);
    }

    printf("%lld\n", res);
    return 0;
}