#include<algorithm>
#include<iostream>
#include<vector>
struct Query
{
unsigned c, a, b;
Query(unsigned c, unsigned a, unsigned b): c(c), a(a), b(b) {}
bool operator<(const Query &q) const
{
return c < q.c;
}
};
unsigned parent[2001], rank[2001];
unsigned getparent(unsigned a)
{
if(a != parent[a])
parent[a] = getparent(parent[a]);
return parent[a];
}
int main()
{
std::ios_base::sync_with_stdio(false);
unsigned n;
std::cin >> n;
std::vector<Query> v;
v.reserve(n * (n + 1) / 2);
for(unsigned i = 0; i < n; ++i)
for(unsigned j = i + 1; j <= n; ++j)
{
unsigned c;
std::cin >> c;
v.emplace_back(c, i, j);
}
std::sort(v.begin(), v.end());
for(unsigned i = 0; i <= n; ++i)
{
parent[i] = i;
rank[i] = 0;
}
unsigned long long w = 0;
unsigned count = 0;
for(const Query &q: v)
{
unsigned a = getparent(q.a), b = getparent(q.b);
if(a != b)
{
if(rank[a] < rank[b])
std::swap(a, b);
if(rank[a] == rank[b])
++rank[a];
parent[b] = a;
w += q.c;
if(++count == n)
break;
}
}
std::cout << w << std::endl;
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 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 | #include<algorithm> #include<iostream> #include<vector> struct Query { unsigned c, a, b; Query(unsigned c, unsigned a, unsigned b): c(c), a(a), b(b) {} bool operator<(const Query &q) const { return c < q.c; } }; unsigned parent[2001], rank[2001]; unsigned getparent(unsigned a) { if(a != parent[a]) parent[a] = getparent(parent[a]); return parent[a]; } int main() { std::ios_base::sync_with_stdio(false); unsigned n; std::cin >> n; std::vector<Query> v; v.reserve(n * (n + 1) / 2); for(unsigned i = 0; i < n; ++i) for(unsigned j = i + 1; j <= n; ++j) { unsigned c; std::cin >> c; v.emplace_back(c, i, j); } std::sort(v.begin(), v.end()); for(unsigned i = 0; i <= n; ++i) { parent[i] = i; rank[i] = 0; } unsigned long long w = 0; unsigned count = 0; for(const Query &q: v) { unsigned a = getparent(q.a), b = getparent(q.b); if(a != b) { if(rank[a] < rank[b]) std::swap(a, b); if(rank[a] == rank[b]) ++rank[a]; parent[b] = a; w += q.c; if(++count == n) break; } } std::cout << w << std::endl; return 0; } |
English