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

using namespace std;
const int N = 2002;
pair<int, pair<int, int> > costs[N * N];
int n;
int m;

int uf[N];

void initUf() {
  for (int i = 0; i <= n; ++i) uf[i] = i;
}

inline int headUf(int i) {
  while (uf[i] != i) {
    uf[i] = uf[uf[i]];
    i = uf[i];
  }
  return i;
}

inline bool checkUf(int i, int j) {
  ++j;
  return headUf(i) == headUf(j);
}

inline void joinUf(int i, int j) {
  ++j;
  uf[headUf(i)] = headUf(j);
}

int main() {
  scanf("%d", &n);
  m = 0;
  for (int i = 0; i < n; ++i) {
    for (int j = i; j < n; ++j) {
      costs[m].second.first = i;
      costs[m].second.second = j;
      scanf("%d", &costs[m].first);
      ++m;
    }
  }
  sort(costs, costs + m);
  long long ret = 0;
  int cnt = n;
  initUf();
  for (int i = 0; cnt; ++i) {
    const int x = costs[i].second.first;
    const int y = costs[i].second.second;
   if (checkUf(x, y)) continue;
    --cnt;
    ret += costs[i].first;
    joinUf(x, y);
  }

  printf("%lld\n", ret);
  return 0;
}