- For sparse graphs
- Time complexity: O (E * logE)
- The right side from small to large, the enumeration to determine whether this point edge connector has been added to the spanning tree, if not joined this edge, or else did not.
-
1 #include <bits/stdc++.h> 2 using namespace std; 3 struct node{ 4 int u,v,w; 5 }e[10005]; 6 int fa[10005]; 7 int cmp(node x,node y){ 8 if(x.w<y.w) return 1; 9 return 0; 10 } 11 int getfather(int x){ 12 if(fa[x]!=x){ 13 fa[x]=getfather(fa[x]); 14 } 15 return fa[x]; 16 } 17 int main(){ 18 int n,m,tot=0; 19 cin>>n; 20 int p=n*n; 21 for(int i=1;i<=n;i++){ 22 for(int j=1;j<=n;j++){ 23 e[++tot].u=i; 24 e[tot].v=j; 25 cin>>e[tot].w; 26 } 27 } 28 sort(e+1,e+p+1,cmp); 29 for(int i=1;i<=p;i++){ 30 fa[i]=i; 31 } 32 int fu,fv,s=0,ans=0; 33 for(int i=1;i<=p;i++){ 34 fu=getfather(e[i].u); 35 fv=getfather(e[i].v); 36 if(fu!=fv){ 37 fa[fu]=fv; 38 ans+=e[i].w; 39 } 40 } 41 cout<<ans<<endl; 42 return 0; 43 }
Kruskal template
Guess you like
Origin www.cnblogs.com/wi1d3on/p/11330916.html
Recommended
Ranking