图论-Kruskal算法求最小生成树

例题:

给定一个 𝑛 个点 𝑚 条边的无向图,图中可能存在重边和自环,边权可能为负数。

求最小生成树的树边权重之和,如果最小生成树不存在则输出 impossible

给定一张边带权的无向图 G=(V,E),其中 V𝑉 表示图中点的集合,E𝐸 表示图中边的集合,n=|V|,m=|E|。

由 V𝑉 中的全部 n𝑛 个顶点和 E𝐸 中 n−1𝑛−1 条边构成的无向连通子图被称为 G𝐺 的一棵生成树,其中边的权值之和最小的生成树被称为无向图 G𝐺 的最小生成树。

输入格式

第一行包含两个整数 n𝑛 和 m𝑚。

接下来 m𝑚 行,每行包含三个整数 u,v,w,表示点 u𝑢 和点 v𝑣 之间存在一条权值为 w𝑤 的边。

输出格式

共一行,若存在最小生成树,则输出一个整数,表示最小生成树的树边权重之和,如果最小生成树不存在则输出 impossible

数据范围

1≤n≤105,
1≤m≤2∗105,
图中涉及边的边权的绝对值均不超过 1000。

输入样例:
4 5
1 2 1
1 3 2
1 4 3
2 3 2
3 4 4
输出样例:
6

代码:

#include<iostream>
#include<cstdio>
#include<string>
#include<cstring>
#include<string.h>
#include<algorithm>
#include<cmath>
#include<vector>
#include<queue>
#include<stack>
#include<map>
#include<set>
#include<unordered_map>
#define int long long
using namespace std;
typedef pair<int,int> PII;
const int N = 2e5 + 10;
int n,m,p[N];
struct NODE{
	int a,b,w;
	bool operator < (const NODE &W) const{
		return w < W.w;
	}
}edge[N];
int find(int x){
	if(p[x] != x)
		p[x] = find(p[x]);
	return p[x];
}
signed main(){
	cin >> n >> m;
	for(int i = 1;i <= n;i ++){
		p[i] = i;
	}
	for(int i = 0;i < m;i ++){
		int a,b,c;
		cin >> a >> b >> c;
		edge[i] = {a,b,c};
	}
	sort(edge,edge+m);
	int cnt = 0,res = 0;
	for(int i = 0;i < m;i ++){
		int a = edge[i].a ,b = edge[i].b,w = edge[i].w;
		if(find(a) != find(b)){
			p[find(a)] = find(b);
			cnt ++;
			res += w;
		}
	}
	if(cnt < n-1) cout << "impossible";
	else cout << res ;
	return 0;
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值