HRBUST 1849 Commodities Center

vjudge

IQ dropped ...

An edge can be found to contribute to other point iff the path points on the right side of the minimum value, if descending according to the edge weights plus side, will each add an edge merging two blocks Unicom, then a block Unicom points within the weight to another point on the link block that edge is the right edge, to the point of the answer can be in the two blocks are coupled Unicom right side \ (* \) another block Unicom points. then this tree can be reconstructed using a similar method to maintain, specifically each time to two Unicom marking root node, then the query is the root to mark a point on this path and point

#include<bits/stdc++.h>
#define LL long long
#define uLL unsigned long long
#define db double

using namespace std;
const int N=2e5+10;
int rd()
{
    int x=0,w=1;char ch=0;
    while(ch<'0'||ch>'9'){if(ch=='-') w=-1;ch=getchar();}
    while(ch>='0'&&ch<='9'){x=(x<<3)+(x<<1)+(ch^48);ch=getchar();}
    return x*w;
}
struct node{int x;LL y;};
struct edge
{
    int x,y,z;
    bool operator < (const edge &bb) const {return z>bb.z;}
}e[N];
int n,pt,ff[N<<1],sz[N<<1],ch[N<<1][2];
LL tg[N<<1],ans;
int findf(int x){return ff[x]==x?x:ff[x]=findf(ff[x]);}
queue<node> q;

int main()
{
    while(~scanf("%d",&n))
    {
        for(int i=1;i<=n;++i)
            ff[i]=i,sz[i]=1;
        for(int i=1;i<=n+n;++i) tg[i]=ch[i][0]=ch[i][1]=0;
        for(int i=1;i<n;++i)
        {
            int x=rd(),y=rd(),z=rd();
            e[i]=(edge){x,y,z};
        }
        sort(e+1,e+n);
        pt=n;
        for(int i=1;i<n;++i)
        {
            int x=findf(e[i].x),y=findf(e[i].y),z=e[i].z;
            tg[x]+=1ll*sz[y]*z,tg[y]+=1ll*sz[x]*z;
            ++pt,ff[x]=ff[y]=ff[pt]=pt,sz[pt]=sz[x]+sz[y],ch[pt][0]=x,ch[pt][1]=y;
        }
        ans=0;
        q.push((node){pt,0});
        while(!q.empty())
        {
            int x=q.front().x;
            LL di=q.front().y;
            q.pop();
            ans=max(ans,di);
            if(!x) continue;
            q.push((node){ch[x][0],di+tg[ch[x][0]]});
            q.push((node){ch[x][1],di+tg[ch[x][1]]});
        }
        printf("%lld\n",ans);
    }
    return 0;
}

Guess you like

Origin www.cnblogs.com/smyjr/p/11432439.html