首页 > 其他 > 详细

POJ - 1251 Jungle Roads (最小生成树&并查集

时间:2019-10-08 18:56:37      阅读:77      评论:0      收藏:0      [点我收藏+]
技术分享图片
#include<iostream>
#include<algorithm>
using namespace std;
int ans=0,tot=0;
const int N = 1e5;
int f[200];
struct ac{
    int v,u,w;
}edge[N];
bool cmp(ac a,ac b){
    return a.w<b.w;
}
inline int find(int x){
    if(x!=f[x])f[x]=find(f[x]);return f[x];
}
inline int join(int x,int y,int w){
    int fx=find(x),fy=find(y);
    if(fx!=fy){
        f[fx]=fy;ans+=w;tot++;
    }
}
int main()
{    
    int n;string a,b;int m,w,cnt=0;
    while(cin>>n&&n){
        //cin.ignore();
        ans=tot=cnt=0;
        for(int i = 1;i <=n;++i)f[i]=i;
        for(int i = 1;i <n;++i){
        cin>>a;cin>>m;
        while(m--){
            cin>>b;cin>>w;
            edge[cnt].u=a[0]-A+1,edge[cnt].v=b[0]-A+1,edge[cnt].w=w;
            cnt++;
        }
        }
        sort(edge,edge+cnt,cmp);
        for(int i = 0;i < cnt;++i){
            join(edge[i].u,edge[i].v,edge[i].w);
            if(tot==n-1)break;
        }
        cout<<ans<<endl;    
    }
    return 0;
}
AC代码

https://vjudge.net/problem/POJ-1251

读题读的有点难受,其余很简单

POJ - 1251 Jungle Roads (最小生成树&并查集

原文:https://www.cnblogs.com/h404nofound/p/11636501.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!