题意:给出一棵树,走过每条边都要花费时间,每个点有一定价值的物品。求在给定时间内能不能从1走到n,如果能,最多可以带走多少价值的物品。
思路:首先对树进行一遍搜索,看能不能从1走到n,如果不能直接输出结果。如果能,记录路径。
因为这条路径上的每条边都需要且只需走一次,每个点的物品都会被取走。所以以这条路径上的每个点作为父节点,对它所有子节点建立分组背包的模型。即相当于走到每一个路径上的点,都对这个点的所有非路径上的子节点建立分组背包。最后再加上路径本身的价值就是最后要求的结果。
#include<stdio.h>
#include<string.h>
const int N=105;
const int T=505;
struct node
{
int son;
int next;
int cost;
} Edge[N*2];
int head[N],vis[N],dp[N][T],v[N],path[N];
int cnt,k;
int Max(int x,int y)
{
if(x>y) return x;
else return y;
}
void AddEdge(int x,int y,int cost)
{
Edge[cnt].son=y,Edge[cnt].next=head[x],Edge[cnt].cost=cost,head[x]=cnt++;
Edge[cnt].son=x,Edge[cnt].next=head[y],Edge[cnt].cost=cost,head[y]=cnt++;
return ;
}
int Find(int father,int n,int cost)
{
if(father==n) return cost;
int u=head[father];
vis[father]=1;
for(int i=u; i!=-1; i=Edge[i].next)
{
int son=Edge[i].son;
if(vis[son]) continue;
path[k++]=son;
int temp=Find(son,n,cost+Edge[i].cost);
if(temp!=-1) return temp;
k--;
}
return -1;
}
void dfs(int father,int kk,int t,int cost)
{
if((kk<k&&father!=path[kk]&&cost<=t)||(kk>=k&&cost<=t)) dp[father][cost]=v[father];
else if(kk<k&&path[kk]==father) memset(dp[father],0,sizeof(dp[father]));
int u=head[father];
vis[father]=1;
for(int i=u; i!=-1; i=Edge[i].next)
{
int son=Edge[i].son;
if(vis[son]) continue;
dfs(son,kk+1,t,Edge[i].cost*2);
for(int j=t; j>=0; j--)
{
for(int l=0; l<=j; l++)
{
if(dp[father][j-l]!=-1)
dp[father][j]=Max(dp[father][j],dp[father][j-l]+dp[son][l]);
}
}
}
return ;
}
int main()
{
int n,t;
while(scanf("%d%d",&n,&t)!=EOF)
{
memset(head,-1,sizeof(head));
cnt=0;
for(int i=1; i<n; i++)
{
int x,y,k;
scanf("%d%d%d",&x,&y,&k);
AddEdge(x,y,k);
}
for(int i=1; i<=n; i++)
scanf("%d",&v[i]);
k=0;
path[k++]=1;
memset(vis,0,sizeof(vis));
int temp=Find(1,n,0);
if(temp>t)
{
printf("Human beings die in pursuit of wealth, and birds die in pursuit of food!\n");
continue;
}
t-=temp;
memset(dp,-1,sizeof(dp));
memset(vis,0,sizeof(vis));
dfs(1,0,t,0);
for(int i=0; i<k; i++)
dp[1][t]+=v[path[i]];
printf("%d\n",dp[1][t]);
}
return 0;
}