POJ - 1251 Jungle Roads 最小生成树模版题

以后刷kuangbin的专题题解不再每篇都写了,只写一道模板题和有价值的变形。

题目链接

POJ-1251

题意

给出全部道路,保留部分道路使得联通的同时花费最小。也就是求最小生成树。

思路

裸的最小生成树,权当试板子

代码

#include<iostream>
#include<algorithm>
#define IOS ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
#define endl "\n"
using namespace std;
	typedef long long ll;
	const int maxn=100000;
	const int inf=0x3f3f3f3f;
	int fa[maxn];
	struct Edge{
    
    
		char u,v;
		int w;
	}edge[maxn];
	
	
	bool cmp(Edge a,Edge b){
    
    
		return a.w<b.w;
	} 
	
	void init(){
    
    
		for(int i=0;i<maxn;i++)
			fa[i]=i;
	}
	
	int find(int x){
    
    
		return x==fa[x]?x:fa[x]=find(fa[x]);
	}
	
	void unite(int x,int y){
    
    
		int fx=find(x),fy=find(y);
		if(fx==fy)
			return ;
		fa[fx]=fy;
	}
	
	int main(){
    
    
		IOS
		int ans,n,cnt;
		while(cin>>n){
    
    
			ans=0,cnt=0;
			if(!n)
				break;
			init();
			n--;
			while(n--){
    
    
				int m;
				char u,v;
				int w;
				cin>>u>>m;
				while(m--){
    
    
					cin>>v>>w;
					edge[cnt].u=u,edge[cnt].v=v,edge[cnt++].w=w;
				}	
			}
			sort(edge,edge+cnt,cmp);
			for(int i=0;i<cnt;i++){
    
    
				int u=edge[i].u,v=edge[i].v;
				if(find(u)!=find(v)){
    
    
					unite(u,v);
					ans+=edge[i].w;
				}
				
			}
			cout<<ans<<endl;
		}
	}
	

猜你喜欢

转载自blog.csdn.net/TheSunspot/article/details/108077268
今日推荐