We need to enumerate the root and then choose as many points from its subtree as possible and pay no more than M, but the complexity of the violence is not right.
Then consider merging the tree from bottom up (there is only one node in each tree, which is itself)
Each tree is a heap, we maintain the number of nodes in the tree and the sum of the salaries, and when combined, the top salary of the heap is constantly popped up until the sum of the salary does not exceed m, then the answer is updated with the number of leadership * nodes.
Found this model is bare left-leaning tree.
#include <algorithm> #include <iostream> #include <cstdlib> #include <cstring> #include < cstdio> #include <cmath> #include <queue>using namespace std; typedef long Long LL; #define N 100010 int l[n],r[n],fa[n];int tree[n],siz[n],d[n]; LL Ld[n],c[n],sum[n]; int n; LL M,ans; int merge (int x,int y) {if (!x) return y; if (!y) return x; if (C[x]<c[y]) swap (x, y); R[x]=merge (R[x],y); if (D[r[x]]>d[l[x]]) swap (l[x],r[x]); d[x]=d[r[x]]+1; SUM[X]=SUM[L[X]]+SUM[R[X]]+C[X]; siz[x]=siz[l[x]]+siz[r[x]]+1; return x;} int main () {scanf ("%d%lld", &n,&m); for (int i=1;i<=n;i++) {scanf ("%d%lld%lld", &fa[i],&c[i],&ld[i]); Tree[i]=i; Siz[i]=1; Sum[i]=c[i]; } for (int i=n;i>=1;i--) {while (sum[tree[i]]>m) Tree[i]=merge (L[tree[i]],r[tree[i]]); Ans=max (Ans,siz[tree[i]]*ld[i]); if (i!=1) Tree[fa[i]]=merge (Tree[fa[i]],tree[i]); } printf ("%lld", ans); return 0;}
"bzoj2809" [Apio2012]dispatching (left-leaning tree)