Prim与Kruskal算法求最小生成树模板

P r i m : Prim: Prim:

#include<bits/stdc++.h>
using namespace std;
const int N=505;
int n,m,u,v,w,g[N][N],dist[N],inf=0x3f3f3f3f;
bool st[N];
int prim(){
    
    
    int res=0;
    memset(dist,0x3f,sizeof dist);
    for(int i=0;i<n;i++){
    
    
        int t=-1;
        for(int j=1;j<=n;j++){
    
    
            if(!st[j]&&(t==-1||dist[t]>dist[j])) t=j;
        }
        if(i&&dist[t]==inf) return inf;
        if(i) res+=dist[t];
        st[t]=1;
        for(int j=1;j<=n;j++) dist[j]=min(dist[j],g[t][j]);
    }
    return res;
}
int main(){
    
    
    memset(g,0x3f,sizeof g);
    cin>>n>>m;
    while(m--){
    
    
        cin>>u>>v>>w;
        g[u][v]=g[v][u]=min(g[u][v],w);
    }
    int t=prim();
    if(t==inf) puts("impossible");
    else cout<<t<<endl;
}

K r u s k a l : Kruskal: Kruskal:

#include<bits/stdc++.h>
using namespace std;
const int N=1e5+5;
int n,m,u,v,w,inf=0x3f3f3f3f,p[N];
struct node{
    
    
    int a,b,c;
}edge[2*N];
bool cmp(node a, node b){
    
    
    return a.c<b.c;
}
int find(int x){
    
    
    if(p[x]!=x) p[x]=find(p[x]);
    return p[x];
}
int kruskal(){
    
    
    sort(edge,edge+m,cmp);
    int res=0,cnt=0;
    for(int i=0;i<m;i++){
    
    
        int a=edge[i].a,b=edge[i].b,w=edge[i].c;
        a=find(a),b=find(b);
        if(a!=b){
    
    
            p[a]=b;
            res+=w;
            cnt++;
        }
    }
    if(cnt<n-1) return inf;
    else return res;
}
int main(){
    
    
    cin>>n>>m;
    for(int i=1;i<=n;i++) p[i]=i;
    for(int i=0;i<m;i++){
    
    
        cin>>u>>v>>w;
        edge[i]={
    
    u,v,w};
    }
    int t=kruskal();
    if(t==inf) puts("impossible");
    else cout<<t<<endl;
}

猜你喜欢

转载自blog.csdn.net/messywind/article/details/113526443