POJ 1251 Jungle Roads G++

本文介绍了一种使用并查集实现最小生成树的算法。通过定义节点结构体和比较函数,对输入数据进行排序,并利用并查集确定是否加入边到最小生成树中,避免形成环路。最终输出最小生成树的总权重。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include <iostream>
#include <map>
#include <vector> 
#include <algorithm>
using namespace std;
//最小生成树 并查集 
struct nod{
	int jl;
	char x;
	char y;
};
bool cmp(nod a, nod b)
{
	return a.jl<b.jl;
}
map<char,char> fa;//并查集 
char find(char x)
{
	while(fa[x]!=x)
	{
		x=fa[x];
	}
	return x;
}
int main()
{
	while(1)
	{
		int n;
		cin>>n;
		if(n==0)
		{
			break;
		}
		vector<nod> ve;
		for(int o=0;o<(n-1);o++)
		{
			char a;
			int m;
			cin>>a>>m;
			for(int i=0;i<m;i++)
			{
				char b;
				int len;
				cin>>b>>len;
				nod t;
				t.x=a;
				t.y=b;
				t.jl=len;
				ve.push_back(t);
			}			
		}
		sort(ve.begin(),ve.end(),cmp);		
		fa.clear();
		for(int i=0;i<26;i++)
		{
			fa['A'+i]=(char)('A'+i);
		} 
		int jg=0;
		for(int i=0;i<ve.size();i++)
		{
			char tx=ve[i].x;
			char ty=ve[i].y;
			if(find(tx)!=find(ty))
			{
				//cout<<find(tx)<<" "<<find(ty)<<endl;
				//cout<<(char)tx<<" "<<(char)ty<<" "<<ve[i].jl<<endl;
				fa[find(tx)]=find(ty);
				//cout<<find(tx)<<" "<<find(ty)<<endl<<endl;
				jg=jg+ve[i].jl;
			}
		}
		cout<<jg<<endl;
	}
	return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值