HDU 1520 Anniversary Party

Problem Description
The president of the Ural State University is going to make an 80'th Anniversary party. The university has a hierarchical structure of employees; that is, the supervisor relation forms a tree rooted at the president. Employees are numbered by integer numbers in a range from 1 to N, The personnel office has ranked each employee with a conviviality rating. In order to make the party fun for all attendees, the president does not want both an employee and his or her immediate supervisor to attend.
 
Input
The first line of the input contains a number N. 1 ≤ N ≤ 6000. 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 the supervisor relation tree goes. Each line of the tree specification has the form
<L> <K>
which means that the K-th employee is an immediate supervisor of L-th employee. Input is ended with the line
0 0

 

Output
The output should contain the maximal total rating of the guests.
 
Sample Input
input output
7
1
1
1
1
1
1
1
1 3
2 3
6 4
7 4
4 5
3 5
0 0
5
 


树形dp。每个结点要么去,要么不去。

置底向上,所以在回溯的时候开始统计。

 

 1 #include <stdio.h>
 2 #include <string.h>
 3 #include <iostream>
 4 #include <vector>
 5 #define MAXN 6100
 6 using namespace std;
 7 
 8 vector<int> V[MAXN];
 9 int ra[MAXN];
10 int visited[MAXN];
11 int dp[MAXN][2];
12 int root;
13 
14 int max(int a, int b){
15     if(a>b)return a;
16     else return b;
17 }
18 
19 void addEdge(int u ,int v){
20     V[u].push_back(v);
21     V[v].push_back(u);
22     if(u==root)
23         root=v;
24 }
25 
26 void dfs(int u){
27     visited[u]=1;
28     dp[u][1]=ra[u];//
29     dp[u][0]=0;//不去
30     int size=V[u].size();
31     for(int i=0; i<size; i++){
32         int to=V[u][i];
33         if(!visited[to]){
34             dfs(to);
35             dp[u][0]+=max(dp[to][1],dp[to][0]);
36             dp[u][1]+=dp[to][0];        
37         }
38     }
39 }
40 
41 int main(){
42     int n;
43     int i;
44     while( scanf("%d",&n)!=EOF ){
45         for(i=1; i<=n; i++){
46             scanf("%d",&ra[i]);
47         }
48         for(i=1; i<=n; i++){
49             V[i].clear();
50         }
51         memset(visited, 0, sizeof(visited));
52         memset(dp ,0 ,sizeof(dp));
53         root=1;
54         int u,v;
55         while( scanf("%d %d",&u ,&v), u!=0&&v!=0 ){
56             addEdge(u,v);
57         }
58         dfs(root);
59         printf("%d\n" ,max(dp[root][0],dp[root][1]));
60     }
61     return 0;
62 }

 

你可能感兴趣的:(part)