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的。
#include <cstdio>
#include <algorithm>
#include <iostream>
#include <cstring>
#include <string>
#include <cmath>
#include <queue>
#include <vector>
using namespace std;
#define N 6010
struct node
{
int nxt, v;
}edge[N];
int head[N], tot;
int w[N], deg[N];
int f[N], t[N];
int s[N]; void add(int u, int v)
{
edge[tot].v = v;
edge[tot].nxt = head[u];
head[u] = tot++;
} void dfs(int s)
{
for(int i = head[s]; ~i; i = edge[i].nxt) {
int v = edge[i].v;
dfs(v);
f[s] += max(t[v], f[v]); //可以选或者不选
t[s] += f[v];
}
} int main()
{
int n;
while(~scanf("%d", &n)) {
memset(f, , sizeof(f));
memset(t, , sizeof(t));
memset(deg, , sizeof(deg));
memset(head, -, sizeof(head));
tot = ;
for(int i = ; i <= n; i++) {
scanf("%d", &w[i]);
t[i] += w[i];
}
int u, v;
while() {
scanf("%d%d", &u, &v);
if(u + v == ) break;
add(v, u);
deg[u]++;
}
int cnt = ;
for(int i = ; i <= n; i++) {
if(deg[i] == ) {
s[cnt++] = i;
}
}
int ans = ;
for(int i = ; i < cnt; i++) {
dfs(s[i]);
ans += max(f[s[i]], t[s[i]]); //万一有很多个根
}
printf("%d\n", ans);
}
return ;
}