POJ 1935 树形DP
2012-10-31 11:41
232 查看
比较好的一道树形DP,与POJ 2486 对比可以加深对树形DP的理解。
题意:给你一棵树和它的根节点,然后给出一些需要遍历的点,问你遍历这些点至少需要多少时间。
解析:dp【i】【0】表示从i节点出发遍历需要的点然后回到i节点,dp【i】【1】则表示不回来,状态想出来了,但是转移的时候并不像之前所做的树形DP一样,要求对于每个子节点都转移(因为有些子树中并没有要求遍历的点),这个怎么处理呢?在DFS的过程中,用plan记录下这棵子树中有没有目标节点,有的话则进行转移,没有则continue;
贴代码:
题意:给你一棵树和它的根节点,然后给出一些需要遍历的点,问你遍历这些点至少需要多少时间。
解析: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; } } }
相关文章推荐
- poj1935(树形dp)
- poj 1935 树形dp,
- POJ 1935 Journey 树形DP
- POJ 1935 树形DP
- poj 1935(树形dp)
- POJ 1935 树形DP
- poj 1935(树形dp)
- poj 2486( 树形dp)
- poj 3140 Contestants Division (树形dp)
- poj 2486 树形dp
- poj 2486 (树形dp (好题))
- POJ 1463 && HDU 1054 Strategic Game (树形DP)
- poj 1463 Strategic game(树形dp)
- POJ 1463 Strategic game (二分图最小覆盖点(匈牙利算法) 或 树形DP)
- poj 1155 TELE (树形背包dp)
- poj 1947 Rebuilding Roads 【树形DP】 【求至少删去树中 多少条边 使得树中节点数为P】
- POJ 2486 Apple Tree - 树形DP
- POJ 2486 Apple Tree(树形dp)
- poj_2486 Apple Tree(树形dp)
- POJ 3659 Cell Phone Network 最小支配集模板题(树形dp)