天天看點

Codeforces Round #646 (Div. 2) E. Tree Shuffling

#include<bits/stdc++.h>
using namespace std;
#define debug puts("YES");
#define rep(x,y,z) for(int (x)=(y);(x)<(z);(x)++)
#define ll long long
#define lrt int l,int r,int rt
#define lson l,mid,rt<<1
#define rson mid+1,r,rt<<1|1
#define mst(a,b) memset((a),(b),sizeof(a))
#define pii pair<int,int>
#define fi first                                  
#define se second
#define mk(x,y) make_pair(x,y)
const int mod=1e9+7;
const int maxn=2e5+10;
const int maxm=5e5+10;
const ll INF=1e18;
ll powmod(ll x,ll y){ll t; for(t=1;y;y>>=1,x=x*x%mod) if(y&1) t=t*x%mod; return t;}
ll gcd(ll x,ll y){
    if(y==0) return x;
    return gcd(y,x%y);
}/*
分析:
用樹形DP的思維去思考問題,
剛開始想的是用價格從小到大的思維,雖然感覺可行但是代碼比較多比較複雜,
看了網上題解才悟到要用樹形DP的思維去思考,
要進行shuffle的隻有0,1或者1,0這樣的數對,是以對于每顆子樹可以維護一個二進制組,
又考慮到目前子樹應該選擇什麼價值其實跟其所有父節點路徑上最小值有關,
這個性質就保證了樹形DP的可行性,因為子樹的選擇肯定目前節點以及以後節點無關了。
具體結合代碼了解。

*/
int n,a[maxn],b[maxn],c[maxn];
ll ans=0;
vector<int> g[maxn];
int dfs(int u,int f){
    a[u]=min(a[u],a[f]);
    int x=0,y=0;
    if(b[u]^c[u]){
        if(b[u]) y++;
        else x++;
    }
    for(auto v:g[u]) if(v^f){
        int tmp=dfs(v,u);
        if(tmp>0) x+=tmp;
        else y-=tmp;
    }
    ans+=2LL*min(x,y)*a[u];
    return x-y;
}

int main(){
    ios::sync_with_stdio(false);/*
    freopen("d://in.txt","r",stdin);
    freopen("d://out.txt","w",stdout);*/
    cin>>n;
    rep(i,1,n+1) cin>>a[i]>>b[i]>>c[i];
    rep(i,1,n){
        int u,v;
        cin>>u>>v;
        g[u].push_back(v);
        g[v].push_back(u);
    }
    a[0]=a[1];
    if(dfs(1,0)) cout<<-1<<"\n";
    else cout<<ans<<"\n";
    return 0;
}
           

繼續閱讀