您的位置:首页 > 移动开发

poj 2486-Apple Tree - 树形DP

2016-04-18 15:24 316 查看
Apple Tree

Time Limit: 1000MSMemory Limit: 65536K
Total Submissions: 9067Accepted: 3014
Description

Wshxzt is a lovely girl. She likes apple very much. One day HX takes her to an apple tree. There are N nodes in the tree. Each node has an amount of apples. Wshxzt starts her happy trip at one node. She can eat up all the apples in the nodes she reaches. HX
is a kind guy. He knows that eating too many can make the lovely girl become fat. So he doesn’t allow Wshxzt to go more than K steps in the tree. It costs one step when she goes from one node to another adjacent node. Wshxzt likes apple very much. So she wants
to eat as many as she can. Can you tell how many apples she can eat in at most K steps.
Input

There are several test cases in the input

Each test case contains three parts.

The first part is two numbers N K, whose meanings we have talked about just now. We denote the nodes by 1 2 ... N. Since it is a tree, each node can reach any other in only one route. (1<=N<=100, 0<=K<=200)

The second part contains N integers (All integers are nonnegative and not bigger than 1000). The ith number is the amount of apples in Node i.

The third part contains N-1 line. There are two numbers A,B in each line, meaning that Node A and Node B are adjacent.

Input will be ended by the end of file.

Note: Wshxzt starts at Node 1.
Output

For each test case, output the maximal numbers of apples Wshxzt can eat at a line.
Sample Input
2 1
0 11
1 2
3 2
0 1 2
1 2
1 3

Sample Output
11
2


#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int maxn = 505;
typedef struct node
{
int v, next;
}Edge;
Edge edge[maxn];
int dp[maxn][maxn][2], val[maxn], head[maxn], tol, n, m;
bool vis[maxn];
//dp[u][j][0]表示以u为根的树经过j步没有回到点u得到的最值
//dp[u][j][1]表示以u为根的树经过j步回到点u得到的最值
void init()
{
memset(head, -1, sizeof(head));
memset(dp, 0, sizeof(dp));
memset(vis, 0, sizeof(vis));
tol = 0;
}

void addedge(int u, int v)
{
edge[tol].v = v;
edge[tol].next = head[u];
head[u] = tol++;
}

void dfs(int u,int fa)
{
for (int i = head[u]; i != -1; i = edge[i].next)
{
int v = edge[i].v;
if (v == fa) continue;
dfs(v, u);
for (int j = m; j >= 0; j--)			//给父节点留下的步数
for (int t = 1; j + t <= m; t++)		//给子树的步数
{
dp[u][j + t][0] = max(dp[u][j + t][0], dp[u][j][1] + dp[v][t - 1][0] + val[v]);
//在这个v节点的子树不回去,所以父节点的状态是1
if (t >= 2) dp[u][j + t][0] = max(dp[u][j + t][0], dp[u][j][0] + dp[v][t - 2][1] + val[v]);
//遍历了v为根的子树然后回去,所以父节点状态是1
if (t >= 2) dp[u][j + t][1] = max(dp[u][j + t][1], dp[u][j][1] + dp[v][t - 2][1] + val[v]);
//都回来的话,u节点的所有子树当然都的回来了
}
}
}

int main()
{
while (scanf("%d%d", &n, &m) != EOF)
{
init();
for (int i = 1; i <= n; i++)
scanf("%d", &val[i]);
for (int i = 1; i < n; i++)
{
int u, v;
scanf("%d%d", &u, &v);
addedge(u, v);
addedge(v, u);
}
dfs(1,-1);
printf("%d\n", max(dp[1][m][1], dp[1][m][0]) + val[1]);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: