Loading

代码-ICPC2018 WF Conquer The World

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef double db;
#define x first
#define y second
#define bg begin()
#define ed end()
#define pb push_back
#define mp make_pair
#define sz(a) int((a).size())
#define R(i,n) for(int i(0);i<(n);++i)
#define L(i,n) for(int i((n)-1);i>=0;--i)
const int iinf=0x3f3f3f3f;
const ll linf=0x3f3f3f3f3f3f3f3f;

//Data
const int N=25e4;
const ll D=1e12;
int n,have[N]; ll ns=0;

//Heap
const int H=1e7;
int h,d[H],ls[H],rs[H]; ll c[H];
void heap_init(){d[0]=-1,c[0]=iinf,h=1;}
int newheap(ll x){c[h]=x; return h++;}
int merge(int u,int v){
    if(!u||!v) return u^v;
    if(c[u]>c[v]) swap(u,v); rs[u]=merge(rs[u],v);
    if(d[ls[u]]<d[rs[u]]) swap(ls[u],rs[u]);
    return d[u]=d[ls[u]]+1,u;
}
void push(int &u,ll x){u=merge(u,newheap(x));}
void pop(int &u){u=merge(ls[u],rs[u]);}

//Graph
ll dep[N]; int qa[N],qb[N];
vector<pair<int,int>> adj[N];
void dfs(int u,int fa){
    for(pair<int,int> v:adj[u])if(v.x!=fa)
        dep[v.x]=dep[u]+v.y,dfs(v.x,u),
        qa[u]=merge(qa[u],qa[v.x]),qb[u]=merge(qb[u],qb[v.x]);
    if(have[u]>0) R(t,have[u]) push(qa[u],dep[u]);
    if(have[u]<0) R(t,-have[u]) push(qb[u],dep[u]-D);
    while(qa[u]&&qb[u]){
        ll a=c[qa[u]],b=c[qb[u]],sm=a+b-(dep[u]<<1);
        if(sm>=0) break; pop(qa[u]),pop(qb[u]);
        push(qa[u],a-sm),push(qb[u],b-sm),ns+=sm;
    }
}

//Main
int main(){
    ios::sync_with_stdio(false);
    cin.tie(0),cout.tie(0);
    cin>>n,heap_init();
    R(i,n-1){
        int u,v,w; cin>>u>>v>>w,--u,--v;
        adj[u].pb(mp(v,w)),adj[v].pb(mp(u,w));
    }
    R(u,n){
        int x,y; cin>>x>>y;
        have[u]=x-y,have[u]<0?ns-=D*have[u]:0;
    }
    dfs(0,-1);
    cout<<ns<<'\n';
    return 0;
}
posted @ 2020-12-26 11:14  George1123  阅读(14)  评论(0编辑  收藏  举报