POJ1251Jungle Roads
题意&思路:
一个旅游景点需要造缆车,使任意两个景点都可以相互到达,问最小花费。
最小生成树(kurskal)模板题,只需要把字母改成整型就好了。
代码:
#include<iostream>
#include<stdio.h>
#include<stdlib.h>
#include<algorithm>
#include<string.h>
#include<ctype.h>
#include<queue>
#include<set>
#include<stack>
#include<cmath>
#include<map>
#define pii pair<int,int>
#define ll long long
#define cl(x) memset(x,0,sizeof(x))
const int N=1e6+10;
const int mod=1e7+9;
const int maxn=0x3f3f3f3f;
const int minn=0xc0c0c0c0;
const int inf=99999999;
using namespace std;
struct edge
{
int u,v,w;
}a[1010];
int fa[30],len;
int cmp(edge x,edge y)
{
return x.w<y.w;
}
int find(int x)
{
if(fa[x]!=x)
fa[x]=find(fa[x]);
return fa[x];
}
int judge(int a,int b)
{
int t1=find(a),t2=find(b);
if(t1!=t2)
{
fa[t1]=t2;
return 1;
}
return 0;
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);cout.tie(0);
int n,i,ans;
while(cin>>n && n)
{
len=0;
ans=0;
for(i=1;i<=n;i++)
fa[i]=i;
for(i=1;i<=n-1;i++)
{
char x,y;
int k,m,j;
cin>>x>>k;
for(j=1;j<=k;j++)
{
cin>>y>>m;
a[++len].u=x-'A'+1;
a[len].v=y-'A'+1;
a[len].w=m;
}
}
sort(a+1,a+len+1,cmp);
int count=0;
for(i=1;i<=len;i++)
{
if(judge(a[i].u,a[i].v))
{
count++;
ans+=a[i].w;
}
if(count==n-1)
break;
}
cout<<ans<<endl;
}
return 0;
}