HDU 1561 The more, The Better
来源:互联网 发布:佳词网络科技集团 诈骗 编辑:程序博客网 时间:2024/06/05 20:06
题意: 给一个树形结构,问最多拿max个城市 ,能获得的最大价值多少,拿下面的一定要先拿上面的。
解题思路:
定义状态dp[i][j] : 当前i节点及其子树下最多选择j个城市的最大值为dp[i][j];
我们考虑到特殊状态:i节点下没有孩子那么dp[i][2,3,4,5...]均为-1(因为多选总比少选好,并且选择完后城市总是有剩余)
1. 判断当前节点P有没有孩子,如果有则令当前节点为P重复(1)操作,如果没有则到(2)操作;
2. 将当前节点P的状态更新到期父节点上,
更新操作为dp[P'father][i] = max(dp[P'father][i], dp[P'father][j]+dp[P][k]) (j + k = i ,j>0,k>0,2<=i<=max_cost,对于每一个i遍历每一种(j,k)组合)
这里的dp[P'father][j] j个城市一定是没有包括P城市的其他j个城市的最大值
直到遍历到root节点即可(dp[0][i])
3.输出dp[0][max_cost]
max_cost 为题目中所给出的最多取几个城市
7 4
2 2
0 1
0 4
2 1
7 1
7 6
2 2
[i]:v 表示 第i个节点的价值为v; [0]root没有价值相当于[0]:0
[0]root
/ \
[2]:1 [3]:4
/ | \
[1]:2 [4]:1 [7]:2
/ \
解题思路:
定义状态dp[i][j] : 当前i节点及其子树下最多选择j个城市的最大值为dp[i][j];
我们考虑到特殊状态:i节点下没有孩子那么dp[i][2,3,4,5...]均为-1(因为多选总比少选好,并且选择完后城市总是有剩余)
1. 判断当前节点P有没有孩子,如果有则令当前节点为P重复(1)操作,如果没有则到(2)操作;
2. 将当前节点P的状态更新到期父节点上,
更新操作为dp[P'father][i] = max(dp[P'father][i], dp[P'father][j]+dp[P][k]) (j + k = i ,j>0,k>0,2<=i<=max_cost,对于每一个i遍历每一种(j,k)组合)
这里的dp[P'father][j] j个城市一定是没有包括P城市的其他j个城市的最大值
直到遍历到root节点即可(dp[0][i])
3.输出dp[0][max_cost]
max_cost 为题目中所给出的最多取几个城市
7 4
2 2
0 1
0 4
2 1
7 1
7 6
2 2
[i]:v 表示 第i个节点的价值为v; [0]root没有价值相当于[0]:0
[0]root
/ \
[2]:1 [3]:4
/ | \
[1]:2 [4]:1 [7]:2
/ \
[5]:1 [6]:6
#include <iostream>#include <cstdio>#include <algorithm>#include <cstring>#include <vector>using namespace std;const int INF=(1<<30);const int M=200+10;vector <int> list[M];int dp[M][M];int n,max_cost;void dfs(int father){ for(int i=0;i<list[father].size();i++){ int child=list[father][i]; if(list[child].size()>0) dfs(child); for(int j=max_cost;j>1;j--) for(int k=1;k<j;k++) dp[father][j]=max(dp[father][j],dp[father][k]+dp[child][j-k]); }}int main(){ while(cin>>n>>max_cost,n&&max_cost) { max_cost++; memset(dp,0,sizeof(dp)); for(int i=1;i<=n;i++) { int a,b; cin>>a>>b; list[a].push_back(i); for(int j=1;j<=max_cost;j++) dp[i][j]=b; } dfs(0); for(int i=0;i<=n;i++) list[i].clear(); cout<<dp[0][max_cost]<<endl; } return 0;}
阅读全文
0 0
- hdoj(hdu)-1561-the more the better
- hdu 1561 The more,The better
- hdu 1561 the more,the better
- Hdu 1561 The more, The Better
- HDU 1561 The more, The Better
- HDU 1561 The more, The Better
- HDU-1561-The more, The Better
- HDU 1561 The more, The Better
- HDU 1561 The more, The Better
- HDU:1561 The more,The Better
- HDU 1561 The more, The Better
- hdu 1561 The more, The Better
- HDU 1561 The more ,The Better
- hdu 1561 The more, The Better DP
- HDU 1561 The more, The Better
- hdu 1561 The more, The Better
- HDU 1561 The more, The Better
- HDU 1561 The more, The Better
- js获取当前页面的URL
- BZOJ 1821 部落划分(二分+并查集)
- 字母图形
- Linux中常用操作命令
- bzoj 1216: [HNOI2003]操作系统
- HDU 1561 The more, The Better
- 利用xinetd实现简单web服务器(镜像站)
- 从零开始的"E"世界(J2SE)
- Hadoop 2.6.5 Windows环境下安装
- 回文数字 观察数字:12321,123321都有一个共同的特征,无论从左到右读还是从右向左读;都是相同的。这样的数字叫做: 回文数字。 本题要求你找到一些5位或6位的十进制数字。满足要求: 该数字
- Python数据结构
- 100 单调性及极值复习 型一:极值点判断;型二:不等式证明
- 自然语言处理课程自学笔记(一)之python正则表达式
- Zookeeper(五)Watcher机制