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

#define MAXN 2007

int n;
struct edge {
	int i, j, c;
} e[(MAXN*(MAXN+1))/2];

bool edgelt(const edge &a, const edge &b)
{
	return a.c < b.c;
}

struct fuset {
	int parent;
	int rank;
} v[MAXN];

int vfind(int x) {
	if (v[x].parent != x)
		v[x].parent = vfind(v[x].parent);
	return v[x].parent;
}

void vunion(int x, int y) {
	x = vfind(x);
	y = vfind(y);
	if (x == y)
		return;
	if (v[x].rank < v[y].rank) {
		v[x].parent = y;
	} else if (v[x].rank > v[y].rank) {
		v[y].parent = x;
	} else {
		v[y].parent = x;
		v[x].rank++;
	}
}
         
int main()
{
	int i, j, k;
	long long res;
	
	scanf("%d", &n);
	k = 0;
	for (i = 0; i < n; i++)
		for (j = i; j < n; j++) {
			scanf("%d", &e[k].c);
			e[k].i = i;
			e[k].j = j+1;
			k++;
		}
	sort(e, e + k, edgelt);
	
	res = 0;
	k = 0;
	for (i = 0; i <= n; i++) {
		v[i].parent = i;
		v[i].rank = 0;
	}
	for (i = 0; k < n; i++) {
		if (vfind(e[i].i) != vfind(e[i].j)) {
			res += (long long) e[i].c;
			vunion(e[i].i, e[i].j);
			k++;
		}
	}
	printf("%lld\n", res);
	return 0;
}