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; } }}
- POJ 1935 树形DP
- poj 1935 树形dp,
- poj 1935(树形dp)
- POJ 1935 树形DP
- POJ 1935 Journey 树形DP
- poj 1770 树形dp
- poj 3342 树形DP
- poj 2486 树形dp
- poj 2486 树形DP
- 【树形dp】POJ 1463
- poj 2486 树形dp
- poj 3140 树形dp
- POJ 2152(树形DP)
- poj 1947 树形dp
- poj 4045 树形dp
- poj 2378 树形 dp
- poj 3107 树形dp
- poj 2057 树形dp
- 有些话,那么悲伤,那么简短_伤感唯美日志
- MIPS平台suspend/resume时GPIO状态控制
- fnd_profile.value的用法
- 将excel导入sqlserver2008的表中引发的问题
- 张家口搞笑方言
- POJ 1935 树形DP
- 开机提示:DISK BOOT FAILURE,INSERT SYSTEM DISK AND PRESS ENTER无法开机的解决办法
- 在EF下使用基于T4模版的POCO实体生成器
- [有關 Cache 的 read/write through/back/allocate 的意義]
- 第四回 关于多线程渲染
- source insight 序列号
- 一边掉眼泪,一边用文字诉说_伤感日志
- 擦亮自己的眼睛去看SQLServer之简单Insert
- MongoDB安装