51Nod1640 天气晴朗的魔法

Problem

51nod魔法学校近日开展了主题为“天气晴朗”的魔法交流活动。
N名魔法师按阵法站好,之后选取N - 1条魔法链将所有魔法师的魔力连接起来,形成一个魔法阵。
魔法链是做法成功与否的关键。每一条魔法链都有一个魔力值V,魔法最终的效果取决于阵中所有魔法链的魔力值的和。
由于逆天改命的魔法过于暴力,所以我们要求阵中的魔法链的魔力值最大值尽可能的小,与此同时,魔力值之和要尽可能的大。
现在给定魔法师人数N,魔法链数目M。求此魔法阵的最大效果。

Solution

最小生成树求最大边最小值,然后求最小生成树。

Code

#include<iostream>
#include<stdio.h>
#include<string>
#include<queue>
#include<cstring>
#include<vector>
#include<algorithm>
#define io_opt ios::sync_with_stdio(false);cin.tie(0);cout.tie(0)
typedef long long ll;
using namespace std;
ll n,m;
ll f[100020];
ll f2[100020];
struct Edge{
    ll u,v,w;
}e[200020]; 
inline int cmp(Edge a,Edge b){
    return a.w<b.w;
}
inline int cmp2(Edge a,Edge b){
    return a.w>b.w;
}
inline ll find(ll x){
    return f[x]==0?x:f[x]=find(f[x]);
}
inline ll find2(ll x){
    return f2[x]==0?x:f2[x]=find2(f2[x]);
}
inline void read(ll &x)
{
    x=0;ll f=0;char ch=getchar();
    while(ch<'0'||ch>'9') {f|=(ch=='-');ch=getchar();}
    while(ch>='0'&&ch<='9'){x=(x<<1)+(x<<3)+(ch^48);ch=getchar();}
    x=f?-x:x;
    return;
}
int main(){
    read(n);read(m);
    ll x,y,z;
    for(int i=1;i<=m;i++){
        //scanf("%d%d%d",&x,&y,&z);
        read(x);
        read(y);read(z);
        e[i]=(Edge){x,y,z};
    }
    sort(e+1,e+1+m,cmp);
    ll cnt=0,sum=0,mx=0;
    for(int i=1;i<=m;i++){
        ll x=find(e[i].u),y=find(e[i].v);
        if(x!=y){
            f[x]=y;
            cnt++;
            //sum+=e[i].w;
            mx=max(mx,e[i].w);
        }
        if(cnt==n-1){
            break;
        }
    }
    cnt=0;
    sort(e+1,e+1+m,cmp2);
    for(int i=1;i<=m;i++){
        ll x=find2(e[i].u),y=find2(e[i].v);
        if(x!=y&&e[i].w<=mx){
            f2[x]=y;
            cnt++;
            sum+=e[i].w;
            //mx=max(mx,e[i].w);
        }
        if(cnt==n-1){
            //cout<<sum<<endl;
            printf("%lld\n",sum);
            break;
        }
    }
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/sz-wcc/p/11761241.html