AcWing859 kruskal算法求最短路
作者:互联网
#include<iostream>
#include<algorithm>
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;
}
标签:cnt,return,int,res,kruskal,find,edges,AcWing859,短路 来源: https://blog.csdn.net/qq_45437180/article/details/122751866