POJ 1935 树形DP

来源:互联网 发布:加拿大大公司 知乎 编辑:程序博客网 时间:2024/05/12 08:47

比较好的一道树形DP,与POJ 2486 对比可以加深对树形DP的理解。

题意:给你一棵树和它的根节点,然后给出一些需要遍历的点,问你遍历这些点至少需要多少时间。

解析:dp【i】【0】表示从i节点出发遍历需要的点然后回到i节点,dp【i】【1】则表示不回来,状态想出来了,但是转移的时候并不像之前所做的树形DP一样,要求对于每个子节点都转移(因为有些子树中并没有要求遍历的点),这个怎么处理呢?在DFS的过程中,用plan记录下这棵子树中有没有目标节点,有的话则进行转移,没有则continue;

贴代码:

#include<stdio.h>#include<string.h>#include<algorithm>using namespace std;const int maxn = 50005;struct edge{    int u,v,w,next;}e[maxn << 1];int head[maxn],tot,dp[maxn][2],n,m,s;bool plan[maxn];void add_edge(int u,int v,int w);void dfs(int f,int u);int main(){    while(scanf("%d%d",&n,&s) != EOF)    {        memset(head,-1,sizeof(head));        memset(plan,false,sizeof(plan));        tot = 0;        for(int i = 1;i < n;i ++)        {            int u,v,w;            scanf("%d%d%d",&u,&v,&w);            add_edge(u,v,w);            add_edge(v,u,w);        }        scanf("%d",&m);        for(int i = 1;i <= m;i ++)        {            int a;            scanf("%d",&a);            plan[a] = true;        }        memset(dp,0,sizeof(dp));        dfs(s,s);      //  for(int i = 1;i <= n;i ++) printf("I:%d  plan:%d\n",i,plan[i]);        printf("%d\n",dp[s][1]);    }    return 0;}void add_edge(int u,int v,int w){    e[tot].u = u,e[tot].v = v,e[tot].w = w;    e[tot].next = head[u],head[u] = tot ++;}void dfs(int f,int u){    for(int i = head[u];i != -1;i = e[i].next)    {        int v = e[i].v;        if(v == f) continue;        dfs(u,v);        plan[u] = (plan[u] | plan[v]);        if(plan[v])        {            dp[u][1] = min(dp[u][1] + dp[v][0] + e[i].w * 2,dp[u][0] + dp[v][1] + e[i].w);            dp[u][0] = dp[u][0] + dp[v][0] + e[i].w * 2;        }    }}