最小生成树总结

· · 个人记录

原理

先按每条边的权值排序,然后贪心选择每条边,判断是否是有效边,如果这个变连接了两个个不在同一个集合中的点,那么它就是有效边。由于排序的缘故,这个第一次连接这个集合的有效边一定是最优的。

当选的边数等于点数减一时,说明已经选完了,后面不会再有有效边,因为这时点已经组成了一棵树也就是联通了,就不需要再连了。

例题

最小生成树模版

模版,按照原理写就行了。

代码

#include<bits/stdc++.h>
#define int long long
using namespace std;
int n,m;
struct edge{
    int u,v,w;
}e[200005];
int fa[5005];
int find(int x){
    if(fa[x]==x)return x;
    fa[x]=find(fa[x]);
    return fa[x];
}
bool cmp(edge a,edge b){
    return a.w<b.w;
}
int cnt;
int ans;
signed main(){
    ios::sync_with_stdio(0),cin.tie(0),cout.tie(0);
    cin>>n>>m;
    for(int i=1;i<=n;i++)fa[i]=i;
    for(int i=1;i<=m;i++)cin>>e[i].u>>e[i].v>>e[i].w;
    sort(e+1,e+1+m,cmp);
    for(int i=1;i<=m;i++){
        int x=find(e[i].u);
        int y=find(e[i].v);
        if(x!=y){
            cnt++;
            fa[x]=y;
            ans+=e[i].w;
            if(cnt==n-1){
                cout<<ans;
                return 0;
            }
        }
    }
    cout<<"orz";
    return 0;
}

另一道例题

边权换成了 (x_i-x_j)^2+(y_i-y_j)^2,存储所有可能的边,然后跑最小生成树,要判断小于 c 才可以连接。

代码

#include<bits/stdc++.h>
#define int long long
using namespace std;
int n,c;
int x[2005],y[2005];
int fa[2005];
int find(int x){
    if(fa[x]==x)return x;
    fa[x]=find(fa[x]);
    return fa[x]; 
}
struct edge{
    int u,v,w;
}e[2005*2005];
int m,cnt;
bool cmp(edge a,edge b){
    return a.w<b.w;
}
int ans;
signed main(){
    ios::sync_with_stdio(0),cin.tie(0),cout.tie(0);
    cin>>n>>c;
    for(int i=1;i<=n;i++){
        cin>>x[i]>>y[i];
        fa[i]=i;
    }
    for(int i=1;i<=n;i++){
        for(int j=i+1;j<=n;j++){
            e[++m]={i,j,pow(x[i]-x[j],2)+pow(y[i]-y[j],2)};
        }
    }
    sort(e+1,e+1+m,cmp);
    for(int i=1;i<=m;i++){
        if(e[i].w<c)continue;
        int x=find(e[i].u);
        int y=find(e[i].v);
        if(x!=y){
            cnt++;
            fa[x]=y;
            ans+=e[i].w;
            if(cnt==n-1){
                cout<<ans;
                return 0;
            }
        }
    }
    cout<<-1;
    return 0;
}