AcWing859 kruskal算法求最短路

#include
#include
using namespace std;
const int N = 2e5 + 10;
int n, m;
int p[N];

struct edge {
	int a, b, w;
	bool operator< (const edge& W)const
	{
		return w < W.w;
	}
};
edge edges[N];

int find(int x) {
	if (x != p[x])p[x] = find(p[x]);
	return p[x];
}

int kruskal() {
	int cnt = 0, res = 0;//cnt统计边数 res统计权重和
	sort(edges, edges + m);
	for (int i = 0; i < m; i++) {
		int a = edges[i].a, b = edges[i].b, w = edges[i].w;
		a = find(a), b = find(b);
		if (a != b) {
		//如果不在一个集合中
			p[a] = b;
			res += w;
			cnt++;
		}
	}
	if (cnt < n - 1)return 0x3f3f3f3f;
	else return res;
}
int main() {
	cin >> n >> m;
	for (int i = 0; i < n; i++)p[i] = i;
	for (int i = 0; i < m; i++) {
		int a, b, w;
		cin >> a >> b >> w;
		edges[i] = { a,b,w };

	}
	int t = kruskal();
	if (t == 0x3f3f3f3f)puts("impossible");
	else cout << t << endl;
}

你可能感兴趣的:(算法,算法,图论,c++,数据结构)