这题kruscal跑的好快,嗯,就是一道板子题,很简单。
输入的话,输入看着很繁琐,所以就用了cin。
#include <iostream>
#include <algorithm>
using namespace std;
struct Edge {
int f, t, c;
bool operator <(const Edge &a)const {
return c < a.c;
}
} edge[1000];
char s, e;
int res, n, m, cost, cnt;
int pre[1000];
int find(int x)
{
if (x==pre[x])
return x;
return pre[x] = find(pre[x]);
}
void unions(int a,int b)
{
int x = find(a);
int y = find(b);
if (x!=y)
pre[x] = y;
}
void kruscal()
{
res = 0;
sort(edge, edge + cnt);
for (int i = 0; i < cnt;i++) {
if (find(edge[i].f)==find(edge[i].t))
continue;
unions(edge[i].f, edge[i].t);
res += edge[i].c;
}
}
int main()
{
ios::sync_with_stdio(false);
while (cin>>n&&n) {
n--;
cnt = 0;
for (int i = 0; i < n+1; i++)
pre[i] = i;
for (int i = 0; i < n; i++)
{
cin >> s >> m;
while (m--)
{
cin >> e >> cost;
edge[cnt].f = s - 'A';
edge[cnt].t = e - 'A';
edge[cnt].c = cost;
cnt++;
}
}
kruscal();
cout << res << endl;
}
return 0;
}