克鲁斯卡尔算法求解最小生成树问题
#include<iostream>
#include<map>
#include<cstring>
#include<string>
#include<vector>
#include<algorithm>
using namespace std;
int par[27];
int v[27];
struct node {
int s, e, cost;
node() {};
node(int _s, int _e, int _cost): s(_s), e(_e), cost(_cost) {};
} nds[450];
void inti(int n) {
int i;
for (i = 0; i < n; i++) {
v[i] = 1;
par[i] = i;
}
}
bool cmp(node n1, node n2) {
return n1.cost < n2.cost;
}
int fd(int id) {
return (par[id] != id) ? par[id] = fd(par[id]) : id;
}
int main() {
int n, i, k, j, from, to, cost, idx, a, b, cnt, ans;
char name[10];
while (scanf("%d", &n) && n) {
inti(n);
idx = 0;
for (i = 0; i < n - 1; i++) {
scanf("%s%d", &name[0], &k);
from = name[0] - 'A';
for (j = 0; j < k; j++) {
scanf("%s%d", &name[0], &cost);
to = name[0] - 'A';
nds[idx++] = node(from, to, cost);
}
}
sort(nds, nds + idx, cmp);
cnt = 0;
ans = 0;
for (i = 0; i < idx; i++) {
a = fd(nds[i].s);
b = fd(nds[i].e);
if (a != b) {
if (v[a] < v[b]) {
v[b] += v[a];
par[a] = b;
} else {
v[a] += v[b];
par[b] = a;
}
cnt++;
ans += nds[i].cost;
if (cnt == n - 1)break;
}
}
printf("%d\n", ans);
}
}