标签:dp
Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 7598 | Accepted: 2548 |
Description
Input
Output
Sample Input
2 1 0 11 1 2 3 2 0 1 2 1 2 1 3
Sample Output
11 2
Source
树形dp
设dp[i][j][0] 表示 在以i为根的子树下走了j步最后不回到i,能够得到的最多苹果数
dp[i][j][1] 表示 在以i为根的子树下走了j步最后回到i,能够得到的最多苹果数
设u为某子树根,v为其中一个儿子节点
dp[u][i][1] = max(dp[u][i][1], dp[v][j - 2][1] + dp[u][i - j][1] + apple[v]);
dp[u][i][0] = max(dp[u][i][0], dp[u][i - j][1] + dp[v][j - 1][0] + apple[v]);
dp[u][i][0] = max(dp[u][i][0], dp[u][i - j][0] + dp[v][j - 2][1] + apple[v]);
/************************************************************************* > File Name: POJ2486.cpp > Author: ALex > Mail: 405045132@qq.com > Created Time: 2015年01月02日 星期五 11时30分01秒 ************************************************************************/ #include <map> #include <set> #include <queue> #include <stack> #include <vector> #include <cmath> #include <cstdio> #include <cstdlib> #include <cstring> #include <iostream> #include <algorithm> using namespace std; vector <int> edge[110]; int dp[110][220][2]; int apple[110]; int n, m; void dfs(int u, int fa) { int size = edge[u].size(); for (int i = 0; i < size; ++i) { int v = edge[u][i]; if (v == fa) { continue; } dfs(v, u); for (int j = m; j >= 1; --j) { for (int k = 1; k <= j; ++k) { if (k >= 2) { dp[u][j][1] = max(dp[u][j][1], dp[u][j - k][1] + dp[v][k - 2][1] + apple[v]); dp[u][j][0] = max(dp[u][j][0], dp[v][k - 2][1] + dp[u][j - k][0] + apple[v]); } dp[u][j][0] = max(dp[u][j][0], dp[u][j - k][1] + dp[v][k - 1][0] + apple[v]); } } } } int main() { int u, v; while (~scanf("%d%d", &n, &m)) { memset (dp, 0, sizeof(dp)); for (int i = 1; i <= n; ++i) { edge[i].clear(); scanf("%d", &apple[i]); } for (int i = 1; i <= n - 1; ++i) { scanf("%d%d", &u, &v); edge[u].push_back(v); edge[v].push_back(u); } dfs(1, -1); printf("%d\n", dp[1][m][0] + apple[1]); } return 0; }
标签:dp
原文地址:http://blog.csdn.net/guard_mine/article/details/42340331