天气晴朗的魔法-kruskal

  • J - 天气晴朗的魔法

  •  51Nod - 1640 
  • 由于逆天改命的魔法过于暴力,所以我们要求阵中的魔法链的魔力值最大值尽可能的小,与此同时,魔力值之和要尽可能的大。
  • #include<bits/stdc++.h>
    using namespace std;
    #define maxn 850000
    #define inf 0x3f3f3f3f
    long long  fa[maxn],tot,n,m,ans,x,y,z,maxx,lim;
    struct node
    {
        int u,v,w;
    } edge[maxn];
    void add(int u,int v,int w)
    {
        edge[tot].u=u;
        edge[tot].v=v;
        edge[tot++].w=w;
    }
    bool cmp(node a,node b)
    {
        return a.w<b.w;
    }
    bool cmp1(node a,node b)
    {
        return a.w>b.w;
    }
    long long  fond(long long x)
    {
        return x==fa[x]?x:fa[x]=fond(fa[x]);
    }
    long long kruskal()
    {
        for(int i=1; i<=n; i++)
            fa[i]=i;
        long long  cnt=0,ans=0;
        for(int i=0; i<tot; i++)
        {
            long long u=edge[i].u;
            long long v=edge[i].v;
            long long w=edge[i].w;
            long long t1=fond(u);
            long long t2=fond(v);
            if(t1!=t2&&w<=lim)
            {
                maxx=max(maxx,w);
                ans+=w;
                fa[t1]=t2;
                cnt++;
            }
            if(cnt==n-1)
                break;
        }
        if(cnt<n-1)
            return -1;
        else
            return ans;
    }
    int main()
    {
        maxx=ans=tot=0;
        lim=inf;
        cin>>n>>m;
        while(m--)
        {
            cin>>x>>y>>z;
            add(x,y,z);
        }
        sort(edge,edge+tot,cmp);
        ans=kruskal();
        lim=maxx;
        ans=0;
        sort(edge,edge+tot,cmp1);
        ans=kruskal();
        cout<<ans<<endl;
        return 0;
    }

猜你喜欢

转载自blog.csdn.net/BePosit/article/details/82048015