#include <algorithm> #include <cstdio> #include <vector> using namespace std; typedef vector<pair<int, pair<int, int> > > Vector; vector<int> parent; void Init(const int n) { parent.resize(0); parent.resize(n, -1); } int Find(int a) { int b = a; while (parent[b] >= 0) b = parent[b]; while (a != b) { const int c = parent[a]; parent[a] = b; a = c; } return a; } void Union(const int a, const int b) { if (parent[a] < parent[b]) { parent[a] += parent[b]; parent[b] = a; } else { parent[b] += parent[a]; parent[a] = b; } } int main() { int n; scanf("%d", &n); Vector v; for (int i = 0; i < n; ++i) for (int j = i + 1; j <= n; ++j) { int c; scanf("%d", &c); v.push_back(make_pair(c, make_pair(i, j))); } sort(v.begin(), v.end()); long long ret = 0; Init(n + 1); for (int k = 0; k < v.size(); ++k) { const int i = Find(v[k].second.first); const int j = Find(v[k].second.second); if (i != j) { Union(i, j); ret += v[k].first; } } printf("%lld\n", ret); return 0; }
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 | #include <algorithm> #include <cstdio> #include <vector> using namespace std; typedef vector<pair<int, pair<int, int> > > Vector; vector<int> parent; void Init(const int n) { parent.resize(0); parent.resize(n, -1); } int Find(int a) { int b = a; while (parent[b] >= 0) b = parent[b]; while (a != b) { const int c = parent[a]; parent[a] = b; a = c; } return a; } void Union(const int a, const int b) { if (parent[a] < parent[b]) { parent[a] += parent[b]; parent[b] = a; } else { parent[b] += parent[a]; parent[a] = b; } } int main() { int n; scanf("%d", &n); Vector v; for (int i = 0; i < n; ++i) for (int j = i + 1; j <= n; ++j) { int c; scanf("%d", &c); v.push_back(make_pair(c, make_pair(i, j))); } sort(v.begin(), v.end()); long long ret = 0; Init(n + 1); for (int k = 0; k < v.size(); ++k) { const int i = Find(v[k].second.first); const int j = Find(v[k].second.second); if (i != j) { Union(i, j); ret += v[k].first; } } printf("%lld\n", ret); return 0; } |