There are N number of farmers who live in N different villages. This N villages form a tree to get the money when the initial X each farmer. Each one operation, a farmer from its own money in, take out any amount of money handed over to a neighboring village farmers. for each farmer given a value v_i, seeking (1) requires a minimum number of operations, so that each farmer finally got the money> = a given value v_i .
Fool knows is a tree dp, but have to work around it
F [i] [j] denotes the subtree i, j with the operations, in that each farmer i eventually got money> = a given value of v conditions give father how much
Backpack tree do: f '[i] [j + k] = f [i] [k] + f [v] [j]
Get
#include<bits/stdc++.h> using namespace std; int n; long long x,f[2001][2001],val[2001],g[2001]; int sz[2001]; vector<int> e[2001]; void merge(int x,int y){ int i,j; for(i=0;i<sz[x];i++)g[i]=f[x][i]; for(i=0;i<sz[x]+sz[y];i++)f[x][i]=-2147483648ll; for(i=0;i<sz[x];i++){ for(j=0;j<sz[y];j++){ if(f[y][j]>=0)f[x][i+j]=max(f[x][i+j],g[i]); f[x][i+j+1]=max(f[x][i+j+1],g[i]+f[y][j]); } }sz[x]+=sz[y]; for(i=1;i<sz[x];i++)f[x][i]=max(f[x][i-1],f[x][i]); } void dfs(int u,int fa){ int i,j; f[u][0]=f[u][1]=x-val[u],sz[u]=1; int v,k; for(i=0;i<e[u].size();i++){ v=e[u][i]; if(v==fa)continue; dfs(v,u),merge(u,v); } } int main(){ int i; cin>>n>>x; for(i=1;i<=n;i++)scanf("%lld",&val[i]); for(i=1;i<n;i++){ int a,b; scanf("%d%d",&a,&b); e[a].push_back(b),e[b].push_back(a); } dfs(1,0); for(i=0;i<n;i++)if(f[1][i]>=0)break; cout<<i<<endl; return 0; }