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
#include<cstdio>
#include<algorithm>
struct Interval {
	short int from;
	short int until;
	int cost;
	Interval(short int from = 0, short int until = 0, int cost = 0):
		from(from), until(until), cost(cost){}
};

bool operator<(Interval const & i1, Interval const & i2){
	return i1.cost < i2.cost;
}

const int N = 2001;
const int M = (N * (N + 1)) / 2;
Interval allIntervals[M];

short int parent[N];
short int rank[N];
short int find(short int v){
	while(parent[v] != v)
		v = parent[v];
	return v;
}

void unite(short int u, short int v){
	u = find(u);
	v = find(v);
	if(rank[u] == rank[v])
		rank[u]++;
	if(rank[u] < rank[v])
		std::swap(u, v);
	parent[v] = u;
}

int main(){
	int n, m = 0;
	scanf("%d", &n);
	for(short int i = 1; i <= n; i++)
		for(short int j = 1; j <= n + 1 - i; j++){
			scanf("%d", &allIntervals[m].cost);
			allIntervals[m].from = i - 1;
			allIntervals[m].until = j + i - 1;
			m++;
		}
	for(short int i = 0; i <= n; i++){
		parent[i] = i;
		rank[i] = 0;
	}
	std::sort(allIntervals, allIntervals + m);
	long long minCost = 0;
	for(Interval *i = allIntervals; i != allIntervals + m; i++){
		short int from = find(i->from);
		short int until = find(i->until);
		if(from != until){
			unite(from, until);
			minCost += i->cost;
		}
	}
	printf("%lld\n", minCost);
	return 0;
}