标签:
最小生成树
Kruskal算法
用C++实现了 UnionFind类
不过用JAVA写这题就一直WA,不知如何是好
#include <cstdio>
#include <algorithm>
using namespace std;
struct Edge
{
int u, v, cost;
};
const int MAX_M = 109 * 108 / 2;
const int MAX_N = 100 + 9;
int n;
bool comp(Edge a, Edge b)
{
if (a.cost < b.cost) return true; else return false;
}
struct UnionFind
{
int n;
int par[MAX_N];
int rank[MAX_N];
UnionFind(int nn)
{
n = nn;
for (int i = 0; i < n; i++) {
par[i] = i;
rank[i] = i;
}
}
int find(int x)
{
if (par[x] == x) return x;
else return par[x] = find(par[x]);
}
void unite(int x, int y)
{
x = find(x);
y = find(y);
if (x == y) return;
if (rank[x] < rank[y]) {
par[x] = y;
} else {
par[y] = x;
if (rank[x] == rank[y]) rank[x]++;
}
}
bool same(int x, int y) {
return find(x) == find(y);
}
void print()
{
for (int i = 0; i < n; i++) {
printf("%d ", par[i]);
}
}
int total()
{
int s = 0;
for (int i = 0; i < n; i++) {
if (par[i] == i) s++;
}
return s;
}
};
void solve()
{
int m = n * (n - 1) / 2;
Edge edges[MAX_M];
for (int i = 0; i < m; i++) {
scanf("%d%d%d", &edges[i].u, &edges[i].v, &edges[i].cost);
}
sort(edges, edges + m, comp);
UnionFind unionFind(n);
int ans = 0;
for (int i = 0; i < m; i++) {
if (!unionFind.same(edges[i].u - 1, edges[i].v - 1)) {
unionFind.unite(edges[i].u - 1, edges[i].v - 1);
ans += edges[i].cost;
}
}
printf("%d\n", ans);
}
int main()
{
for (;;) {
scanf("%d", &n);
if (n == 0) break;
solve();
}
}
标签:
原文地址:http://blog.csdn.net/yyecust/article/details/51328789