您的位置:首页 > 其它

POJ2342(树形dp)

2016-07-09 18:13 218 查看
Description

There is going to be a party to celebrate the 80-th Anniversary of the Ural State University. The University has a hierarchical structure of employees. It means that the supervisor relation forms a tree rooted at the rector V. E. Tretyakov. In order to make the party funny for every one, the rector does not want both an employee and his or her immediate supervisor to be present. The personnel office has evaluated conviviality of each employee, so everyone has some number (rating) attached to him or her. Your task is to make a list of guests with the maximal possible sum of guests’ conviviality ratings.

Input

Employees are numbered from 1 to N. A first line of input contains a number N. 1 <= N <= 6 000. Each of the subsequent N lines contains the conviviality rating of the corresponding employee. Conviviality rating is an integer number in a range from -128 to 127. After that go N – 1 lines that describe a supervisor relation tree. Each line of the tree specification has the form:

L K

It means that the K-th employee is an immediate supervisor of the L-th employee. Input is ended with the line

0 0

Output

Output should contain the maximal sum of guests’ ratings.

Sample Input

7

1

1

1

1

1

1

1

1 3

2 3

6 4

7 4

4 5

3 5

0 0

Sample Output

5

题意:要举办一个聚会,聚会里面直属上下级不能同时出现,而且每个人都有一个rating,问你如何让聚会中总rating最大

题解:这是一道树形dp题,d[a][0]表示不选这个人,也就是不选i这个节点时这个节点加上他的子树的rating的最大值,d[a][1]表示选这个节点时,这个节点加上他的子树的rating的最大值。(b为a的孩子节点)

d[a][0] += max (d[b][1], d[b][0]);

d[a][1] += d[b][0];

#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include <algorithm>
#include <map>
#include <queue>
#include <cmath>
#include <vector>

using namespace std;

const int maxn = 6000 + 5;
int n, d[maxn][2] = {0}, maxs = -128 * 6000 - 5;
bool leaf[maxn] = {false};
vector<int> child[maxn];

void dp(int a)
{
for (int i = 0; i < child[a].size(); i++) {
int b = child[a][i];
dp(b);
d[a][0] += max (d[b][1], d[b][0]);
d[a][1] += d[b][0];
}
}

int main()
{
#ifndef ONLINE_JUDGE
freopen ("in.txt", "r", stdin);
#endif // ONLINE_JUDGE
while (scanf ("%d", &n) != EOF) {
for (int i = 0; i < n; i++) {
child[i].clear();
}
memset (d, 0, sizeof(d));
memset (leaf, false, sizeof(leaf));
for (int i = 0; i < n; i++) {
scanf ("%d", &d[i][1]);
}
for (int i = 0;  ; i++) {
int a, b;
scanf ("%d%d", &a, &b);
if (a == 0 && b == 0) break;
child[b - 1].push_back(a - 1);
leaf[a - 1] = true;
}
int j;
for (j = 0; j < n; j++) {
if (leaf[j] == false) {//找到根节点,从根节点开始跑
dp (j);
break;
}
}
printf ("%d\n", max (d[j][0], d[j][1]));
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: