Description
Input
Output
Sample Input
0 3 3
1 3 5
2 2 2
1 2 4
2 3 1
Sample Output
1 #include<cstdio> 2 #include<algorithm> 3 #include<math.h> 4 #include<string.h> 5 using namespace std; 6 typedef long long ll; 7 const ll maxn=1e5+10; 8 ll c[maxn],val[maxn]; 9 ll limit; 10 ll f[maxn],dis[maxn]; 11 ll ch[maxn][2]; 12 ll sumlimit[maxn]; 13 ll sumsize[maxn]; 14 ll ans; 15 struct node 16 { 17 ll v,next; 18 }G[maxn]; ll head[maxn];ll num=-1; 19 void build(ll u,ll v) 20 { 21 G[++num].v=v;G[num].next=head[u];head[u]=num; 22 } 23 ll Merge(ll x,ll y) 24 { 25 if(!x||!y) return x+y; 26 if(c[x]<c[y]) swap(x,y); 27 ch[x][1]=Merge(ch[x][1],y); 28 f[ch[x][1]]=x; 29 if(dis[ch[x][0]]<dis[ch[x][1]]) swap(ch[x][1],ch[x][0]); 30 dis[x]=dis[ch[x][1]]+1; 31 return x; 32 } 33 void dfs(ll u) 34 { 35 for(ll i=head[u];i!=-1;i=G[i].next){ 36 ll v=G[i].v; 37 dfs(v); 38 sumlimit[u]+=sumlimit[v]; 39 sumsize[u]+=sumsize[v]; 40 f[u]=Merge(f[u],f[v]); 41 } 42 f[u]=Merge(f[u],u); 43 sumlimit[u]+=c[u]; 44 sumsize[u]++; 45 while(sumlimit[u]>limit){ 46 sumlimit[u]-=c[f[u]]; 47 sumsize[u]--; 48 f[u]=Merge(ch[f[u]][0],ch[f[u]][1]); 49 } 50 ans=max(ans,1ll*sumsize[u]*val[u]); 51 return; 52 53 } 54 int main() 55 { 56 ll n; 57 memset(head,-1,sizeof(head)); 58 scanf("%lld%lld",&n,&limit); 59 for(ll i=1;i<=n;i++){ 60 ll u; 61 scanf("%lld%lld%lld",&u,&c[i],&val[i]); 62 build(u,i); 63 } 64 dfs(0); 65 printf("%lld\n",ans); 66 return 0; 67 }