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
#include<stdio.h>
#include<iostream>
#include<stdlib.h>
#include<vector>
#include<list>
#include<math.h>
#include<algorithm>
#include<string>
#include<set>
#include<queue>
#define limit 4048576
#define inf 9223372036854775807ll
#define iinf 2147483647
#define mp make_pair
#define pb push_back
#define rep(i,k,n) for(int i=k;i<n;i++)
using namespace std;
int id[limit],treesz[limit],n,temp;
priority_queue< pair<int, pair<int,int> >, vector< pair<int, pair<int,int> > >, greater<pair<int, pair<int,int> > > > c;
int anc(int u){
    while(id[u]!=u){
            id[u]=id[id[u]];
            u=id[u];
    }
    return u;
}
void uunion(int u, int v){
    u=anc(u);
    v=anc(v);
    if(u!=v){
        if(treesz[u]>treesz[v]){
                id[v]=u;
                treesz[u]+=treesz[v];
        }
        else{
                id[u]=v;
                treesz[v]+=treesz[u];
        }
    }
}
int main(){
    scanf("%d",&n);
    rep(i,0,n) rep(j,i+1,n+1){
        scanf("%d",&temp);
        c.push(mp(temp,mp(i,j)));
    }
    long long ans=0;
    rep(i,0,n+1) id[i]=i;
    while(c.size()){
        if(anc(c.top().second.first)!=anc(c.top().second.second)){
            ans+=c.top().first;
            uunion(c.top().second.first,c.top().second.second);
        }
        c.pop();
    }
    printf("%lld",ans);
    return 0;
}