hdu4276 The Ghost Blows Light(树型dp)

来源:互联网 发布:qq飞车淘宝刷徒弟流程 编辑:程序博客网 时间:2024/05/01 03:30

hdu4276

题目

就是有一棵树,每个节点有财宝,每条边有花费时间,限定时间T内,从1出发,最后要到N,问最多拿到的财宝是多少。

思路

首先求出1到n的最短路,在递归的过程中记录花费的时间并且将路径上的边权改成0。之后判断花费时间于T的大小,小的话就进行一次树形dp,dp[i][j]表示从i出发花费j时间最后得到的最多价值,因为1到n的路径只会走一次,而且我们已经把它改成0了,所以一定会走到,其他的点我们一定会走两次,所以是2*w。

代码

#include <cstdio>#include <algorithm>#include <vector>#include <cstring>#include <iostream>#include <stack>#include <queue>using namespace std;typedef long long ll;const int maxn=110;int tot,head[maxn],n,T,sum;int value[maxn],dp[maxn][510];struct node{    int next;    int to;    int w;} edge[maxn*2];void addedge(int from,int to,int w){    edge[tot].to=to;    edge[tot].next=head[from];    edge[tot].w=w;    head[from]=tot++;}int dfs1(int u,int fa,int rt){    if(rt==u) return 1;    for(int i=head[u]; ~i; i=edge[i].next)    {        int v=edge[i].to;        int w=edge[i].w;        if(v==fa) continue;        sum+=w;        edge[i].w=0;        if(dfs1(v,u,rt)) return 1;        sum-=w;        edge[i].w=w;    }    return 0;}void dfs2(int u,int fa){    for(int i=0; i<=T; i++) dp[u][i]=value[u];    for(int i=head[u]; ~i; i=edge[i].next)    {        int v=edge[i].to;        int w=edge[i].w;        if(v==fa) continue;        dfs2(v,u);        for(int j=T; j>=2*w; j--)            for(int k=0; k+2*w<=j; k++)            {                dp[u][j]=max(dp[u][j],dp[u][j-2*w-k]+dp[v][k]);            }    }}int main(){    while(scanf("%d %d",&n,&T)!=EOF)    {        tot=0;        memset(head,-1,sizeof(head));        for(int i=0; i<n-1; i++)        {            int a,b,c;            scanf("%d %d %d",&a,&b,&c);            addedge(a,b,c);            addedge(b,a,c);        }        for(int i=1; i<=n; i++)            scanf("%d",&value[i]);        sum=0;        dfs1(1,-1,n);        if(sum>T) printf("Human beings die in pursuit of wealth, and birds die in pursuit of food!\n");        else        {            T-=sum;            memset(dp,0,sizeof(dp));            dfs2(1,-1);            printf("%d\n",dp[1][T])  ;        }    }    return 0;}
0 0
原创粉丝点击