The Ghost Blows Light HDU - 4276(树形dp+背包+最短路)

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

思路:先从1到n跑一遍最短路,同时把最短路径的权重都变成0,在跑一次树上背包即可

代码:

#include <iostream>
#include <stdio.h>
#include <string.h>
#include <algorithm>
#include <queue>
#include <map>
#include <vector>
#include <set>
#include <string>
#include <math.h>
#include <stack>
typedef long long ll;
using namespace std;
const int maxn=1e3+10;
const int INF=1<<20;
const int mod=1e9+7;
struct Edge
{
    int u,v,w,next;
}edge[maxn<<1];
int num,n,T;
int head[maxn];
int dp[maxn][maxn];
int d[maxn];
int h[maxn];
int pre[maxn];
void addEdge(int u,int v,int w)
{
    edge[num].u=u;
    edge[num].v=v;
    edge[num].w=w;
    edge[num].next=head[u];
    head[u]=num++;
}
void init()
{
    memset(head,-1,sizeof(head));
    memset(dp,0,sizeof(dp));
    num=0;
}
void spfa()
{
    memset(pre,-1,sizeof(pre));
    fill(d,d+n+1,INF);
    queue<int> que;
    que.push(1);
    d[1]=0;
    while(que.empty()==0)
    {
        int v=que.front();
        que.pop();
        for(int i=head[v];i!=-1;i=edge[i].next)
        {
            int nxt=edge[i].v,w=edge[i].w;
            if(d[nxt]>d[v]+w)
            {
                d[nxt]=d[v]+w;
                pre[nxt]=i;
                que.push(nxt);
            }
        }
    }
}
void dfs(int u,int fa)
{
    for(int i=0;i<=T;i++)
    {
        dp[u][i]=h[u];
    }
    for(int i=head[u];i!=-1;i=edge[i].next)
    {
        int v=edge[i].v,w=edge[i].w;
        if(v==fa) continue;
        dfs(v,u);
        int tmp=2*w;
        for(int j=T;j>=tmp;j--)
        {
            for(int k=0;k<=j-tmp;k++)
            {
                dp[u][j]=max(dp[u][j],dp[u][j-k-tmp]+dp[v][k]);
            }
        }
    }
}
int main(int argc, char const *argv[])
{
    #ifndef ONLINE_JUDGE
        freopen("in.txt","r",stdin);
        freopen("out.txt","w",stdout);
    #endif
    while(scanf("%d%d",&n,&T)!=EOF)
    {
        init();
        for(int i=1;i<n;i++)
        {
            int x,y,w;
            scanf("%d%d%d",&x,&y,&w);
            addEdge(x,y,w);
            addEdge(y,x,w);
        }
        for(int i=1;i<=n;i++)
        {
            scanf("%d",&h[i]);
        }
        spfa();
        if(d[n]>T)
        {
            printf("Human beings die in pursuit of wealth, and birds die in pursuit of food!\n");
            continue;
        }
        int tmp=n;
        T-=d[n];
        for(int u=pre[tmp];u!=-1;u=pre[edge[u].u]) 
        {
            edge[u].w=0;
            edge[u^1].w=0;
        }
        dfs(1,-1);
        printf("%d\n",dp[1][T]);
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_40774175/article/details/81369276