最小生成树Kruskal裸题
康复训练ing
值得一提地是 用getchar() 一直在RE 最后换成了cin 才A掉
#include <iostream>
#include <cstdio>
#include <cstring>
#include <queue>
#include <algorithm>
using namespace std;
#define MAX_V (30)
#define MAX_E (100)
int n, tot = 0;
int first[MAX_V], nxt[MAX_E<<1], fa[MAX_V<<1];
struct edge{
int from, to, cost;
}es[MAX_E<<1];
void init()
{
tot = 0;
memset(first,-1,sizeof(first));
memset(nxt,0,sizeof(nxt));
memset(es,0,sizeof(es));
for(int i = 1; i <= n; ++ i)
fa[i] = i;
}
bool cmp(edge a, edge b)
{
return a.cost < b.cost;
}
int find(int x)
{
int t = x;
while(fa[x] != x)
x = fa[x];
while(t != fa[t])
{
fa[t] = x;
t = fa[t];
}
return x;
}
int Kruskal()
{
int ans = 0;
sort(es+1,es+tot+1,cmp);
for(int i = 1; i <= tot; ++ i)
{
int fu = find(es[i].from);
int fv = find(es[i].to);
if(fu != fv)
{
fa[fu] = fv;
ans += es[i].cost;
}
es[i].from = es[i].to = es[i].from = 0;
}
return ans;
}
int main()
{
while(scanf("%d", &n))
{
if(n == 0) break;
init();
char c, d;
for(int i = 1; i < n; ++ i)
{
// c = getchar();
// if(c < 'A' || c > 'Z') c = getchar();
cin >> c;
int m;
scanf("%d", &m);
int cst;
while(m--)
{
// scanf(" %c %d", &d, &cst);
cin >> d >> cst;
es[++tot] = (edge){(int)(c-64), (int)(d-64), cst};
}
}
printf("%d\n", Kruskal());
}
return 0;
}