代码及解释
#include <iostream>
#include <algorithm>
using std::cin;
using std::cout;
using std::endl;
char set[1000];
int n,k;
struct edge {
char s,e;
int w;
} e[1000];
inline bool cmp(edge a,edge b) {
return a.w<b.w;
}
char find_f(char x) {
return set[x] == x ? x : set[x] = find_f(set[x]);
}
int Kruskal() {
int sum = 0;
for(int i = 0; i < k; ++i) {
char x = find_f(e[i].s);
char y=find_f(e[i].e);
if(x != y) {
set[x] = y;
sum += e[i].w;
}
}
return sum;
}
int main() {
while(cin >> n && n) {
char rs, re;
int m, rw;
k=0;
n--;
while(n--) {
cin >> rs >> m;
while(m--) {
cin >> re >> rw;
e[k].s = rs;
e[k].e = re;
e[k].w = rw;
k++;
}
}
for(char i = 'A'; i <= 'Z'; ++i)
set[i] = i;
std::sort(e, e + k, cmp);
cout << Kruskal() << endl;
}
return 0;
}