poj 2486 Apple Tree (树形dp)
来源:互联网 发布:哪个公司网络信号最好 编辑:程序博客网 时间:2024/05/19 18:14
题意:一颗树,n个点(1-n),n-1条边,每个点上有一个权值,求从1出发,走V步,最多能遍历到的权值
我们把背包的思想用到这里来,做的步数相当于背包的容量,点上的权值相当于价值,给定一定的背包容量,求最多能装进背包的价值
设dp[0][s][j]表示从s(当前根节点)出发,走 j 步,回到s所能获得的最大权值
dp[1][s][j]表示从s(当前根节点)出发,走j步,不回到s所能获得的最大权值
现在我们就可以分配背包容量了:父节点与子节点分配背包容量,从而设计出状态转移方程
主要思想:
s返回,t返回
s不返回,t返回(走向t子树,t子树返回之后走向s的其他子树,然后不回到s)
s返回,t不返回(遍历s的其他子树后返回s,返回之后走向t子树,然后不回到t)
没有都不返回,肯定有一方有一个返回的过程,再去另一边的子树的
总结起来一句话,要么去s的其他子树呆着,要么去t子树呆着,要么回到s点
1、在t子树返回,其他子树也返回,即回到当前根节点s
2,、不返回根节点,但在t子树返回,即相当于从t出发走k步返回t的最优值 加上 从s出发走j-k步到其他子树不返回的最优值,中间有s与t连接起来,其实就等于从s出发遍历t子树后(dp[0][t][k])又回到s(这一步多了中间的来回两步),再走出去(其他子树)【dp[1][s][j-k]】,不回来
3、不返回根节点,在t子树也不返回,等价于从s出发遍历其他子树,回到s(dp[0][s][j-k]),再走向t子树,不回到t(dp[1][t][k]),这个过程s-t只走了一步
dp[0][s][j+2]=Max(dp[0][s][j+2],dp[0][t][k]+dp[0][s][j-k]);//从s出发,要回到s,需要多走两步s-t,t-s,分配给t子树k步,其他子树j-k步,都返回
dp[1][s][j+2]=Max(dp[1][s][j+2],dp[0][t][k]+dp[1][s][j-k]);//不回到s(去s的其他子树),在t子树返回,同样有多出两步
dp[1][s][j+1]=Max(dp[1][s][j+1],dp[1][t][k]+dp[0][s][j-k]);//先遍历s的其他子树,回到s,遍历t子树,在当前子树t不返回,多走一步
要有双向的路径,就是s可以回到他的父节点
#include<cstdio>#include<cstring>#include<vector>#include<algorithm>using namespace std;int value[105],used[105]; int n,k;int dp[2][105][210];vector <int>g[105];void dfs(int s){ used[s]=1; for(int i=0;i<=k;i++) {dp[1][s][i]=dp[0][s][i]=value[s]; } for(int i=0;i<g[s].size();i++) { int t=g[s][i]; if(used[t])continue; dfs(t); for(int j=k;j>=0;j--) for(int q=0;q<=j;q++) { dp[0][s][j+2]= max(dp[0][s][j+2],dp[0][t][q]+dp[0][s][j-q]); dp[1][s][j+2]= max(dp[1][s][j+2],dp[0][t][q]+dp[1][s][j-q]); dp[1][s][j+1]= max(dp[1][s][j+1],dp[1][t][q]+dp[0][s][j-q]); } }}int main(){ while(~scanf("%d%d",&n,&k)) { for(int i=0;i<=100;i++) g[i].clear(); for(int i=1;i<=n;i++) scanf("%d",&value[i]); int a,b; for(int i=1;i<n;i++) {scanf("%d%d",&a,&b); g[a].push_back(b); g[b].push_back(a); } memset(dp,0,sizeof(dp)); memset(used,false,sizeof(used)); dfs(1); printf("%d\n",dp[1][1][k]); } return 0;}
- poj 2486 Apple Tree(树形dp)
- POJ 2486 Apple Tree(树形dp)
- POJ 2486 Apple Tree(树形dp)
- POJ 2486Apple Tree (树形dp)
- POJ 2486 Apple Tree(树形dp)
- poj 2486 Apple Tree (树形dp)
- poj 2486 Apple Tree (树形dp)
- POJ 2486 Apple Tree (树形 dp)
- poj 2486 Apple Tree(DP-树形DP)
- POJ 2486 Apple Tree 树形DP
- POJ 2486 Apple Tree 树形dp
- POJ--2486--Apple Tree--树形回溯DP
- 【树形DP】 POJ 2486 Apple Tree
- poj 2486 Apple Tree(经典树形DP)
- poj 2486 Apple Tree 树形dp
- *(中等) 树形dp POJ 2486 Apple Tree
- poj 2486 Apple Tree (树形dp)
- Apple Tree - POJ 2486 树形dp
- POI导出Execle前后台实例
- Android 使用字体图标
- Swift06-字面量
- Spark学习笔记 --- 任务调度的逻辑图
- 结构-行为-样式
- poj 2486 Apple Tree (树形dp)
- SpringMVC的HandlerExceptionResolver
- Spring boot(16) spring boot 线上故障 上传文件出错:org.springframework.web.multipart.MultipartException: Could
- Android 计算缓存大小和清除缓存
- Dalvik虚拟机
- MongoDB 3.X 用户权限控制
- (2)MyBatis之增删改查
- Spring Boot 使用 Druid 和监控配置
- 四大法则教你合理选择MOS管