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
#include <cstdio>
#include <algorithm>
#include <vector>

static const int MAX_N = 2003;

std::vector<std::pair<int, std::pair<int, int> > > elements;

int fu[MAX_N];

int find(int x)
{
	if(fu[x] == x)
		return x;
	return fu[x] = find(fu[x]);
}

void make_union(int x, int y){
	fu[find(x)] = find(y);
}

int main()
{
	int n;
	scanf("%d", &n);
	
	for(int i = 1; i <= n; ++i)
		for(int j = i; j <= n; ++j)
		{
			int tmp;
			scanf("%d", &tmp);
			elements.push_back(std::make_pair(tmp, std::make_pair(i, j+1)));
		}

	for (int i = 0; i < MAX_N; ++i)
		fu[i] = i;
		
	std::sort(elements.begin(), elements.end());
	
	long long result = 0;
	
	for(auto element : elements)
	{
		int f1 = find(element.second.first);
		int f2 = find(element.second.second);
		if (f1 != f2)
		{
			result += element.first;
			make_union(f1, f2);
		}
	}
	
	printf("%lld\n", result);
	return 0;
}