【图论】测试题A - Networking

题意

一个无向图,n个顶点,m条边,要求求出最小生成树的所有边之和

思路

整道题还是比较裸的(写完之后看了一下似乎是kruskal算法)

储存好图之后按照边的权值大小排序,遍历每一个边,保证每次选择的是最短的边

代码

#include<map>
#include<cmath>
#include<stack>
#include<queue>
#include<cstdio>
#include<vector>
#include<string>
#include<cstring>
#include<iostream>
#include<algorithm>
#define Endl "\n"
using namespace std;
typedef long long ll;
typedef pair<int,int> pii;
const int maxn = 1e5+5;
const int INF = 0x3f3f3f;
const int mod = 1e9 + 7;
inline ll read(){
	ll x = 0, f = 1; char ch; ch = getchar();
	while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
	while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();}
	return x*f;
}

struct g{
	int a,b,w;
};
struct g e[5000];
int n,m,ans,cnt;
int fa[5000];
void init()
{
	cnt=0;
	ans=0;
	memset(e,0,sizeof(e));
	for(int i=1;i<=n;i++)
		fa[i]=i;
}
int cmp(g a , g b)
{
	return a.w<b.w;
}
int getf(int a)
{
	if(a==fa[a]) return fa[a];
	fa[a]=getf(fa[a]);
	return fa[a];
}
bool mrge(int a,int b)
{
	int k=getf(a);
	int v=getf(b);
	if(k!=v)
	{
		fa[v]=k;
		return 1;
	}
	return 0;
}
void solve() {
	init();
	m=read();
	for(int i=1;i<=m;i++)
	{
//		cout<<i<<" "<<m<<Endl;
		e[i].a=read(),e[i].b=read(),e[i].w=read(); 
	}
	
	sort(e+1,e+m+1,cmp);
	
	for(int i=1;i<=m;i++)
	{
//		cout<<"here"<<Endl;
		if(mrge(e[i].a,e[i].b))
		{
			cnt++;
			ans+=e[i].w;
		}
		if(cnt==n-1) break;
	}
	cout<<ans<<Endl;
	return ; 
} 

int main() {
	while(cin>>n&&n)
		solve();
	return 0;
} 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值