//这一题敲完直接AC,吓尿了
//kruskal做的,prim也行
#include <iostream>
#include <algorithm>
#include <cstring>
using namespace std;
const int MAXN = 28;
const int MAXM = 76;
int T;
struct edge
{
int u,v,w;
}edges[MAXM];
int Father[MAXN];
int Rank[MAXN];
int N,M;
int sumcost;
int cmp(const void *a, const void *b) //按公路维护费用排序
{
edge aa = *(const edge *)a;
edge bb = *(const edge *)b;
return aa.w - bb.w;
}
void Make_Set()
{
for(int i = 0; i <= N; i++)
{
Father[i] = i;
Rank[i] = 1;
}
}
int Find(int x)
{
while(x != Father[x])
x = Father[x];
return x;
}
void Union(int x,int y)
{
x = Find(x);
y = Find(y);
if( x == y)
return;
if(Rank[x] > Rank[y])
{
Father[y] = x;
Rank[x] += Rank[y];
}
else
{
Father[x] = y;
Rank[y] += Rank[x];
}
}
void Kruskal()
{
int u,v;
Make_Set();
for(int i = 0; i < M; i++)
{
u = edges[i].u;
v = edges[i].v;
if(Find(u) != Find(v)) //如果不形成回路
{
sumcost += edges[i].w;
Union(u,v);
}
}
}
int main()
{
while(cin>>T)
{
if(T == 0)
break;
int u,n,v,w;
char ch;
N = T;
M = 0;
for(int i = 0; i < T-1; i++)
{
cin>>ch;
u = ch - 'A';
cin>>n;
for(int j = 0; j < n; j++)
{
cin>>ch;
v = ch - 'A';
cin>>w;
edges[M].u = u;
edges[M].v = v;
edges[M].w = w;
M++;
}
}
qsort(edges,M,sizeof(edges[0]),cmp);
sumcost = 0;
Kruskal();
cout<<sumcost<<endl;
}
return 0;
}
poj 1251 kruskal
最新推荐文章于 2019-05-09 11:06:46 发布