http://acm.split.hdu.edu.cn/showproblem.php?pid=1520
Anniversary party
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
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
题意:给出一个员工关系图(树),每个员工有一个上司和一个快乐度,现在要参加一个派对,不能让员工和直接上司一起到场,求现场能达到的最大快乐度是多少。
思路:比较水的题目,一个 t[i] 记录第 i 个员工出场的时候以 i 为根的树的总值,f[i] 记录第 i 个员工不出场的时候以 i 为根的树的总值。
f[i]的时候他的儿子可选可不选(一开始只考虑选的情况错了几次,有时候不选更优),t[i]的时候他的儿子一定不可选。
还有一个坑点是有多个case的。
1 #include <cstdio> 2 #include <algorithm> 3 #include <iostream> 4 #include <cstring> 5 #include <string> 6 #include <cmath> 7 #include <queue> 8 #include <vector> 9 using namespace std; 10 #define N 6010 11 struct node 12 { 13 int nxt, v; 14 }edge[N]; 15 int head[N], tot; 16 int w[N], deg[N]; 17 int f[N], t[N]; 18 int s[N]; 19 20 void add(int u, int v) 21 { 22 edge[tot].v = v; 23 edge[tot].nxt = head[u]; 24 head[u] = tot++; 25 } 26 27 void dfs(int s) 28 { 29 for(int i = head[s]; ~i; i = edge[i].nxt) { 30 int v = edge[i].v; 31 dfs(v); 32 f[s] += max(t[v], f[v]); //可以选或者不选 33 t[s] += f[v]; 34 } 35 } 36 37 int main() 38 { 39 int n; 40 while(~scanf("%d", &n)) { 41 memset(f, 0, sizeof(f)); 42 memset(t, 0, sizeof(t)); 43 memset(deg, 0, sizeof(deg)); 44 memset(head, -1, sizeof(head)); 45 tot = 0; 46 for(int i = 1; i <= n; i++) { 47 scanf("%d", &w[i]); 48 t[i] += w[i]; 49 } 50 int u, v; 51 while(1) { 52 scanf("%d%d", &u, &v); 53 if(u + v == 0) break; 54 add(v, u); 55 deg[u]++; 56 } 57 int cnt = 0; 58 for(int i = 1; i <= n; i++) { 59 if(deg[i] == 0) { 60 s[cnt++] = i; 61 } 62 } 63 int ans = 0; 64 for(int i = 0; i < cnt; i++) { 65 dfs(s[i]); 66 ans += max(f[s[i]], t[s[i]]); //万一有很多个根 67 } 68 printf("%d\n", ans); 69 } 70 return 0; 71 }