hdu4424 并查集+贪心+思维

#include<bits/stdc++.h>
#define MAXN 200005
using namespace std;

long long n,tot;
long long f[MAXN],cnt[MAXN],ans[MAXN];
struct node{
    long long from,to,cost,next,tp;
}e[MAXN<<1]; 

void init(){
    tot=0;
    memset(ans,0,sizeof(ans));
    for(int i=1;i<=n;i++)f[i]=i,cnt[i]=1;
}

void add(long long x,long long y,long long z){
    tot++;
    e[tot].from=x;
    e[tot].to=y;
    e[tot].cost=z;
}

long long found(long long x){
    if(f[x]==x)return x;
    int fa=found(f[x]);
    f[x]=fa;
    return fa;
}

bool cmp(node x,node y){
    return x.cost>y.cost;
}

int main(){
    while(scanf("%lld",&n)==1){
        init();
        for(int i=1;i<n;i++){
            long long x,y,z;
            scanf("%lld%lld%lld",&x,&y,&z);
            add(x,y,z);    
        }
        sort(e+1,e+1+tot,cmp);
        for(int i=1;i<n;i++){
            long long ff=found(e[i].from),fy=found(e[i].to);
            if(ff!=fy){
                if(ans[fy]+cnt[ff]*e[i].cost>ans[ff]+cnt[fy]*e[i].cost)swap(ff,fy);
                ans[ff]+=(cnt[fy]*e[i].cost);
                cnt[ff]+=cnt[fy];
                f[fy]=ff;
            }
        }
        cout<<ans[found(1)]<<endl;
    }
}
View Code

一开始有点想法....

待更

猜你喜欢

转载自www.cnblogs.com/shatianming/p/12295900.html