kruskal(最小生成树)
#include<iostream> #include<cstring> #include<algorithm> using namespace std; const int N = 100010, M = 200010, INF = 0x3f3f3f3f; int n, m; int p[N]; struct Edge { int a, b, w; bool operator< (const Edge &W)const//重载比较符合表示以权值大小排序 { return w < W.w; } }edges[M]; int find(int x) { if(p[x] != x) p[x] = find(p[x]); return p[x]; } int kruskal() { sort(edges, edges+m); for(int i=1; i<=n; i++) p[i] = i; int res = 0, cnt = 0; 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;//res加的是,最小生成树边的权重之和 cnt++;//当前加入多少边 } } if(cnt < n-1) return INF;//判断一共加了多少条边,若是cnt小于n-1则说明不连通 return res; } int main() { scanf("%d%d", &n, &m); for(int i=0; i<m; i++) { int a, b, w; scanf("%d%d%d", &a, &b, &w); edges[i] = {a, b, w}; } int t = kruskal(); if(t == INF) puts("impossible"); else printf("%d\n", t); }