思路
- 叶结点只能挂在叶结点上,而父结点可以挂在父结点上也可以挂在叶结点上
- 所以优先从叶结点开始挂装饰品,利用叶结点的花费来更新父结点的花费,并记录该父结点下的叶结点装饰品的数量
代码
// Problem: Tree Decoration
// Contest: NowCoder
// URL: https://ac.nowcoder.com/acm/problem/24623
// Memory Limit: 65536 MB
// Time Limit: 2000 ms
//
// Powered by CP Editor (https://cpeditor.org)
#include <bits/stdc++.h>
using namespace std;
#define pb push_back
#define mp(aa,bb) make_pair(aa,bb)
#define _for(i,b) for(int i=(0);i<(b);i++)
#define rep(i,a,b) for(int i=(a);i<=(b);i++)
#define per(i,b,a) for(int i=(b);i>=(a);i--)
#define mst(abc,bca) memset(abc,bca,sizeof abc)
#define X first
#define Y second
#define lowbit(a) (a&(-a))
#define debug(a) cout<<#a<<":"<<a<<"\n"
typedef long long ll;
typedef pair<int,int> pii;
typedef unsigned long long ull;
typedef long double ld;
const int N=100010;
const int INF=0x3f3f3f3f;
const int mod=1e9+7;
const double eps=1e-6;
const double PI=acos(-1.0);
int n,root;
int p[N];
ll t[N],c[N];
vector<int> g[N];
ll ans;
ll dfs(int u,int fa){
ll sum=0;
for(int v:g[u]){
if(v==fa) continue;
sum+=dfs(v,u);
t[u]=min(t[u],t[v]);
}
if(sum<c[u]){
ans+=(c[u]-sum)*t[u];
return c[u];
}
return sum;
}
void solve(){
cin>>n;
rep(i,1,n){
cin>>p[i]>>c[i]>>t[i];
if(p[i]==-1) root=i;
else{
g[i].pb(p[i]);
g[p[i]].pb(i);
}
}
dfs(root,0);
cout<<ans<<"\n";
}
int main(){
ios::sync_with_stdio(0);cin.tie(0);
// int t;cin>>t;while(t--)
solve();
return 0;
}