krustral算法加并查集,按题给要求维护并查集~
#include<bits/stdc++.h> using namespace std; const int maxn=1014; const int inf=1e9; int N,M,x,y; int c,w; struct edge { int u; int v; int w; }Edge[maxn*4]; int mst[maxn]; int num[maxn]; int father[maxn]; bool cmp (edge a,edge b) { return a.w<b.w; } int findfather (int x) { int a=x; while (x!=father[x]) x=father[x]; while (a!=father[a]) { int z=a; a=father[a]; father[z]=x; } return x; } vector<int> g[maxn]; int main () { scanf ("%d %d %d",&N,&M,&c); for (int i=0;i<N;i++) father[i]=i,num[i]=1; for (int i=0;i<M;i++) { scanf ("%d %d %d",&Edge[i].u,&Edge[i].v,&Edge[i].w); } sort (Edge,Edge+M,cmp); for (int i=0;i<M;i++) { int u=Edge[i].u; int v=Edge[i].v; int faU=findfather(u); int faV=findfather(v); if (faU==faV) continue; if ((Edge[i].w<=mst[faU]+c/num[faU])&&(Edge[i].w<=mst[faV]+c/num[faV])) { if (faU<faV) swap (faU,faV); father[faU]=faV; if (Edge[i].w>mst[faV]) mst[faV]=Edge[i].w; num[faV]+=num[faU]; } } for (int i=0;i<N;i++) g[findfather(i)].push_back(i); for (int i=0;i<N;i++) { if (g[i].size()==0) continue; sort (g[i].begin(),g[i].end()); for (int j=0;j<g[i].size();j++) { if (j!=0) printf (" "); printf ("%d",g[i][j]); } printf (" "); } return 0; }