【CCF】最优灌溉 最小生成树

【AC】

#include<iostream>
#include<cstdio>
#include<string>
#include<cstring>
#include<algorithm>
#include<vector>

using namespace std;
const int maxn=1e3+2;
const int maxm=1e5+2;
int n,m;
struct edge{
    int u;
    int v;
    int w;
    bool operator < (const edge& a) const{
        return w<a.w;
    }
}e[2*maxm];
int cnt,ans;
int fa[maxn];
int tot;
void init(){
    tot=0;
    for(int i=1;i<=n;i++) fa[i]=i;
}
void add(int u,int v,int w){
    e[tot].u=u;
    e[tot].v=v;
    e[tot].w=w;
    tot++;
}
int find(int x){
    return x==fa[x]?x:fa[x]=find(fa[x]);
}
void merge(int u,int v,int w){
    int fu=find(u);
    int fv=find(v);
    if(fu!=fv){
        ans+=w;
        cnt++;
        fa[fu]=fv;
    }
}
int work(){
    cnt=0;
    ans=0;
    sort(e,e+tot);
    for(int i=0;i<tot;i++){
        
        int u=e[i].u;
        int v=e[i].v;
        int w=e[i].w;
        merge(u,v,w);
        if(cnt==n-1) return ans;
    }
}
int main(){
    while(~scanf("%d%d",&n,&m)){
        init();
        int u,v,w;
        for(int i=1;i<=m;i++){
            scanf("%d%d%d",&u,&v,&w);
            add(u,v,w);
            add(v,u,w);
        }
        int ans=work();
        printf("%d
",ans);
    }
     
    return 0; 
}
原文地址:https://www.cnblogs.com/itcsl/p/9192957.html