题意:
Problem 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 T 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
翻译成汉语再翻译成直男的视野,大概意思就是给出一个树,树上n个点,每个点都有一个权值,不能同时选取相邻的两个节点,问满足上述条件选取节点的最大权值和
思路:
这道题是一道典型的树形dp,我们利用邻接表记录节点之间的关系,由根到叶进行dp。
对于dp【i】【0】代表以该节点为根节点的子树且根节点不被选取的最大权值和
dp【i】【1】代表以该节点为根节点的子树且根节点被选取的最大权值和
我们可以得到父子之间的递推关系式子:
//当父节点不被选取时,它的dp[inx][0]等于每个儿子节点被选取和不被选取的最大值的和
dp[inx][0] += max(dp[son][1], dp[son][0]);
//当父节点被选取时,它的dp[inx][1]等于每个儿子节不被选取的和 + 父亲节点的权值
dp[inx][1] = val[inx];
dp[inx][1] += dp[son][0];
代码:
#include <stdio.h>
#include <vector>
#include <string.h>
#include <algorithm>
#define N 6005
#define ll long long
using namespace std;
int n;
int val[N];
int pre[N];
vector<int>point[N];
ll dp[N][2]; //1参加 0不参加
void init() {
int a, b;
memset(dp, 0, sizeof(dp));
for (int i = 1; i <= n; i++) {
pre[i] = i;
point[i].clear();
}
for (int i = 1; i <= n; i ++) {
scanf("%d", &val[i]);
}
while (scanf("%d%d", &a, &b) == 2) {
if (a == 0 && b == 0) break;
point[b].push_back(a);
pre[a] = b;
}
return;
}
void dfs(int inx) {
dp[inx][1] = val[inx];
for (int i = 0; i < point[inx].size(); i++) {
int son = point[inx][i];
dfs(son);
dp[inx][0] += max(dp[son][1], dp[son][0]);
dp[inx][1] += dp[son][0];
}
}
int main () {
while (scanf("%d", &n) == 1) {
init();
int root;
for (int i = 1; i <= n; i++) {
if(pre[i] == i) {
root = i;
break;
}
}
dfs(root);
printf("%d\n", max(dp[root][1], dp[root][0]));
}
return 0;
}
如果有写的不对或者不全面的地方 可通过主页的联系方式进行指正,谢谢