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
86
87
88
#include <stdio.h>
#include <algorithm>
#include <vector>

using namespace std;

typedef long long LL;

const int MaxN = 2003,
          MaxSiz = 2100001;

/* find-union; niby takie kombinowanie niepotrzebne, ale Kruskal to Kruskal */
int fu_pnt[MaxN], fu_rank[MaxN];
void fu_init(int N){
	for(int i = 0; i <= N; i++){
		fu_pnt[i] = i;
		fu_rank[i] = 1;
	}
}
int fu_find(int v){
	if(fu_pnt[v] == v)
		return v;
	else
		return (fu_pnt[v] = fu_find(fu_pnt[v]));
}
bool fu_union(int a, int b){
	a = fu_find(a); b = fu_find(b);
	
	if(a == b) return false;
	
	if(fu_rank[a] < fu_rank[b]){
		fu_pnt[a] = b;
		fu_rank[b]++;
	} else {
		fu_pnt[b] = a;
		fu_rank[a]++;
	}
	return true;
}
/* koniec find-union */


struct Cost { /* koszt z wejscia */
	int L, R, c;
	Cost(int _L=0, int _R=0, int _c=0) : L(_L), R(_R), c(_c) {}
	bool operator<(const Cost &C) const {
		return c < C.c;
	}
};

Cost hints[MaxSiz];
int N, numHints;

void input(){
	scanf("%d", &N);
	
	fu_init(N);
	numHints = 0;
	for(int i = 0; i < N; i++){
		for(int j = i; j < N; j++){
			int c;
			scanf("%d", &c);
			
			hints[numHints++] = Cost(i, j+1, c);
		}
	}
}

LL process(){
	LL res = 0;
	
	sort(hints, hints+numHints);
	
	for(int i = 0; i < numHints; i++){
		int L = hints[i].L,
		    R = hints[i].R,
		    c = hints[i].c;
		
		if(fu_union(L, R)) res += c;
	}
	return res;
}


int main(){
	input();
	printf("%lld\n", process());
}