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
#include <cstdio>
#include <vector>
#include <algorithm>
using namespace std;
int parent[ 2005 ];
int find( int a ){
    if (parent[a] == a){
        return a;
    }
    else {
        parent[a] = find( parent[a] );
        return parent[a];
    }
}
void _union(int a, int b){
    a = find( a );
    b = find( b );
    parent[ a ] = b;
}
vector < pair < int, pair <int,int> > > kr;
int main(){
    int n;
    scanf("%d",&n);
    for (int i = 1; i <= n; i++){
        parent[i] = i;
        for (int j = i; j <= n; j++){
            int a;
            scanf("%d",&a);
            kr.push_back( make_pair( a, make_pair( i-1, j )));
        }
    }
    sort( kr.begin(), kr.end() );
    long long result = 0;
    for (int i = 0; i < kr.size(); i++){
        if (find( kr[i].second.first ) != find( kr[i].second.second )){
            _union( kr[i].second.first, kr[i].second.second );
            result += kr[i].first;
        }
    }
    printf("%lld\n", result);
}