Kruskal模板

  • 适合稀疏图
  • 时间复杂度:O(E*logE)
  • 把边权从小到大,枚举判断此边连接的点是否已经加入生成树,没有的话就加入这条边,否则不加。
  •  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 } 
原文地址:https://www.cnblogs.com/wi1d3on/p/11330916.html