#C10L09P05. C10.L09.最小生成树.Kruskal算法模板

C10.L09.最小生成树.Kruskal算法模板

题目描述

给定一个 nn 个点 mm 条边的无向图,图中可能存在重边和自环,边权可能为负数。求最小生成树的树边权重之和,如果最小生成树不存在则输出 impossible。给定一张边带权的无向图 G=(V,E)G=(V,E),其中 VV 表示图中点的集合,EE 表示图中边的集合, n=Vn=|V|m=Em=|E|。由 VV 中的全部 nn 个顶点和 EEn1n−1 条边构成的无向连通子图被称为 GG 的一棵生成树,其中边的权值之和最小的生成树被称为无向图 GG 的最小生成树。

输入格式

第一行包含两个整数 nn ( 1n5001 \le n \le 500 } 和 mm ( 1m1000001 \le m \le 100000 )。

接下来 mm 行,每行包含三个整数 uu,vv,ww,表示点 uu 和点 vv 之间存在一条权值为 ww 的边 ( w10000w \le 10000 )。

输出格式

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

样例

4 5
1 2 1
1 3 2
1 4 3
2 3 2
3 4 4
6

完成程序

#include<bits/stdc++.h>
using namespace std;
const int N = 1e6 + 10;
int a[N], n, m, res, cnt;
struct node{
	int x;
	int y;
	int z;
}nodes[N] ;

bool cmp(node x, node y){
	return x.z < y.z;
}

int findp(int x){
	if (a[x]!=x) a[x]=findp(a[x]);
	return a[x];
}

int main(){

	cin>>n>>m;
	for(int i=1;i<=n;i++) a[i] = i;
	for(int i=1;i<= m; i++) {//存储图
		cin >> nodes[i].x >> nodes[i].y >> nodes[i].z;
	}
	sort(nodes+1,nodes+m+1,cmp);//从小到大排序

	for(int i=1;i<=m; i++){
		int x = nodes[i].x;
		int y = nodes[i].y;
		int z = nodes[i].z;
		int xp = findp(x);
		int yp = findp(y);
		if (__填空(1)__) {//是否存在环
			__填空(2)__;
			cnt++;
			a[xp] = yp;
		}
	}

	if(__填空(3)__) cout<<"impossible"<<endl;
	else cout<<res<<endl;

	return 0;
}

填空(1):{{ input(1) }}

填空(2):{{ input(2) }}

填空(3):{{ input(3) }}