Make It Connected 题解

· · 个人记录

题目描述:求要使图连通,最少需要花费多少枚硬币

思路:我们可以在b中选一个费用最小的点,让他跟其他点建边,这样可以让边权最小,边权为b[wei]+b[i],记住把题目给的边也加上,从按边权小到大排一遍序,最后求一遍最小生成树

代码:

#include<bits/stdc++.h>
using namespace std;
#define int long long

int f[1000010];
int b[1000010];
int n,m,ans;
struct db{
    int x,y,w;
}a[1000010];
bool cmp(db a,db b){
    return a.w<b.w;
}
int gf(int x){
    if(x==f[x]){
        return x;
    }
    f[x]=gf(f[x]);
    return f[x];
}
void merge(int x,int y,int w){
    x=gf(x),y=gf(y);
    if(x!=y){
        f[y]=x;
        ans+=w;
    }
}
signed main() {
    ios::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
    cin>>n>>m;
    int mi=1e18,wei=0;
    for(int i=1; i<=n; i++){
        f[i]=i;
        cin>>b[i];
        if(mi>b[i]){
            mi=b[i];
            wei=i; 
        }
    }
    for(int i=1; i<=n; i++){
        if(i==wei){
            continue;
        }
        a[i].x=wei,a[i].y=i,a[i].w=b[wei]+b[i];
    }
    for(int i=n+1; i<=n+m; i++){
        cin>>a[i].x>>a[i].y>>a[i].w;        
    }
    sort(a+1,a+n+m+1,cmp);
    for(int i=1; i<=n+m; i++){
        merge(a[i].x,a[i].y,a[i].w);
    }
    cout<<ans;
    return 0;
}