树上的背包
#include <iostream> #include <cstdio> #include <algorithm> #include <vector> #include <queue> #include <cmath> #include <cstring> using namespace std; const int MAXN = 110; int n, m; struct Node { int num,cost, val; }room[MAXN]; int dp[MAXN][MAXN]; bool vis[MAXN]; vector<int>edge[MAXN]; void dfs(int u){ vis[u]=1; if(u!=1&&edge[u].size()==1&&!room[u].cost){ room[u].cost=1; } for (int i = room[u].cost; i <= m; i++){ dp[u][i] = room[u].val; } for(int i=0;i<edge[u].size();i++){ int v = edge[u][i]; if(vis[v]) continue; dfs(v); for(int j=m ;j >= room[u].cost; j--){ for(int k=1;k<=j-room[u].cost;k++){ dp[u][j]=max(dp[u][j],dp[u][j-k]+dp[v][k]); } } } } int main(){ while(scanf("%d%d",&n,&m)==2){ if(n==-1 && m == -1) break; for(int i=1;i<=n;i++){ int x; edge[i].clear(); scanf("%d%d",&x,&room[i].val); room[i].cost = x/20 + (x%20!=0); } for(int i=1;i<n;i++){ int a,b; scanf("%d%d",&a,&b); edge[a].push_back(b); edge[b].push_back(a); } if(m==0) { puts("0"); continue; } memset(dp,0,sizeof(dp)); memset(vis,0,sizeof(vis)); dfs(1); printf("%d\n",dp[1][m]); } }
时间: 2024-12-13 04:21:18