Greedy from the bottom up.
Each time to the son sort, greedy small to big delete, until cannot delete.
#include <algorithm> #include <iostream> #include <cstdlib> #include <cstring> #include < cstdio> #include <cmath> #include <queue>using namespace std; #define N 2000010int n,m;struct Edge{int to, Next;} E[n];int head[n<<1];int cnt;int a[n],c[n];int ans;int x,xx;void link (int u,int v) {e[++cnt]= (edge) {V,head[u]}; head[u]=cnt;} void Dfs (int x) {for (int i=head[x];i;i=e[i].next) DFS (e[i].to); cnt=0;for (int i=head[x];i;i=e[i].next) C[++cnt]=a[e[i] . To];sort (c+1,c+cnt+1); for (int i=1;i<=cnt;i++) {if (a[x]+c[i]-1>m) break;a[x]+= (c[i]-1), ans++;}} int main () {scanf ("%d%d", &n,&m), for (int i=1;i<=n;i++) scanf ("%d", &a[i]), and for (int i=1;i<=n;i++) { scanf ("%d", &x), a[i]+=x;for (int j=1;j<=x;j++) scanf ("%d", &xx), link (i,xx+1);} DFS (1);p rintf ("%d\n", ans); return 0;}
"bzoj4027" [HEOI2015] rabbit and cherry blossom