題目描述
通向自由的鑰匙被放n個房間裏,這n個房間由n-1條走廊連接。但是每個房間裏都有特別的保護魔法,在它的作用下,我無法通過這個房間,也無法取得其中的鑰匙。雖然我可以通過消耗能量來破壞房間裏的魔法,但是我的能量是有限的。那麼,如果我最先站在1號房間(1號房間的保護魔法依然是有效的,也就是,如果不耗費能量,我無法通過1號房間,也無法取得房間中的鑰匙),如果我擁有的能量爲P,我最多能取得多少鑰匙?
經典的樹形DP
#include <stdio.h>
#include <string.h>
#include <iostream>
#include <algorithm>
#define N 100+5
using namespace std;
int n,m,f[N][N],r[N],l[N],key[N],cost[N];
bool vis[N],graph[N][N];
inline int read()
{
int x = 0, f = 1; char ch = getchar();
while (ch < '0' || ch > '9') { if (ch == '-') f = -1; ch = getchar(); }
while (ch >= '0' && ch <= '9') { x = x * 10 + ch - '0'; ch = getchar(); }
return x * f;
}
void Pre(int x)
{
vis[x]=true;
for(int i=1;i<=n;++i)
if(!vis[i]&&graph[x][i])
{
r[i]=l[x];
l[x]=i;
Pre(i);
}
return;
}
void DFS(int x)
{
if(l[x])DFS(l[x]);
if(r[x])DFS(r[x]);
for(int i=0;i<=m;++i)
{
f[x][i]=f[r[x]][i];
for(int j=0;j<=i-cost[x];++j)
f[x][i]=max(f[x][i],key[x]+f[l[x]][j]+f[r[x]][i-j-cost[x]]);
}
}
int main()
{
cin>>n>>m;
for(int i=1;i<=n;++i)
cost[i]=read(),key[i]=read();
for(int i=1;i<n;++i)
{int tmp1=read(),tmp2=read();graph[tmp1][tmp2]=graph[tmp2][tmp1]=true;}
Pre(1);
DFS(1);
cout<<f[1][m];
}