树形DP
例题
A - Anniversary party(树形DP)
题意有n个人要开一个PARTY,编号1到n,每个人都有一个欢乐值,并且每个人都有一个直接上司,为了让气氛更好,要求在这n个人中选一些人去参加PARTY,并且选出的这些人中任意两个人之间都没有直接上司或直接下属关系,求选出人的最大欢乐值。
思路:一个模板树形dp。dp[i][1] 选i这个人
dp[i][0]不选这个人。和普通dp差不多,只不过在树上进行,需要用dfs便利然后取最大值即可
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.
输入
There are several cases. In each case,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. Case is ended with the line
0 0
输出
Output should contain the maximal sum of guests' ratings.
输入样例
7
1
1
1
1
1
1
1
1 3
2 3
6 4
7 4
4 5
3 5
0 0
输出样例
5
代码
#include <iostream>
#include<cstdio>
#include<algorithm>
#include<cstdlib>
#include<cstring>
#include<set>
#include<string>
#include<stack>
#include<vector>
using namespace std;
typedef long long ll ;
const int maxn = 2e5 + 10 ;
vector<int>e[maxn] ;
int dp[maxn][2];
bool vis[maxn] ;
void dfs(int u)
{
vis[u] = 1 ;
for(int i = 0; i < (int)e[u].size(); i++)
{
int v = e[u][i] ;
if(!vis[v])
{
dfs(v);
dp[u][1]+=dp[v][0];
dp[u][0]+=max(dp[v][0],dp[v][1]);
}
}
}
int main()
{
int n ;
int x, y ;
while(scanf("%d",&n)!=EOF)
{
for(int i = 1; i <= n; i++)
{
cin >> dp[i][1];
dp[i][0] = 0;
}
memset(vis,0,sizeof(vis));
while(scanf("%d %d",&x,&y)!=EOF)
{
if(x==0&&y==0)
break;
e[x].push_back(y);
e[y].push_back(x);
}
dfs(1);
int y = max(dp[1][1],dp[1][0]);
printf("%d\n",y);
for(int i = 0;i<=n;i++)
e[i].clear();
}
return 0;
}