$kruskal$算法
按边权从小到大排序,并查集合并即可。
#include<cstdio> #include<algorithm> using namespace std; int fa[200005]; int n,m; struct abc { int from,to,w; } q[200005]; int getfa(int x) { if(fa[x] == x)return fa[x]; else return fa[x] = getfa(fa[x]); } bool cmp(abc x,abc y) { return x.w < y.w; } int kruskal() { int ans = 0; for(int i = 1; i <= n; i++) { fa[i] = i; } sort(q+1,q+m+1,cmp); for(int i = 1; i <= m; i++) { int l = getfa(q[i].from); int r = getfa(q[i].to); if(l != r) { fa[l] = r; ans += q[i].w; } } return ans; } int main() { scanf("%d%d",&n,&m); for(int i = 1; i <= m; i++) { scanf("%d%d%d",&q[i].from,&q[i].to,&q[i].w); } printf("%d",kruskal()); return 0; }