Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 11395 | Accepted: 6565 |
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 N – 1 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
Source
Ural State University Internal Contest October'2000 Students Session
题目大意:题目意思就是,有一颗关系树,如果某个人去,那么某个人的father 就不能去,以某个人为father的人,也都不能去; 如果这个人不去,那么这个人的father可以去或不去。
思路:这个的话,就是树型dp,用记忆化搜索实现代码
dp【maxn】【2】每个人的话,有两种状态,0-不去,1-去;
flag的话就是表示去或者不去,用fa表示他的父亲节点,x表示当前的位置
#include <iostream>
#include <cstdio>
#include <queue>
#include <cstring>
#include<vector>
using namespace std;
const int maxn = 10000;
int w[maxn];
int n;
vector<int> v[maxn];
int dp[maxn][2];
int dfs(int x, int flag, int fa)
{
if (dp[x][flag] != -1)
{
return dp[x][flag];
}
dp[x][flag] = 0;
if (flag == 1) //代表如果他去那么以他为父亲节点的那些都不能去
{
dp[x][flag] = w[x];
for (int i = 0; i < v[x].size(); i++)
{
int u = v[x][i];
if (u != fa)
{
dp[x][flag] += dfs(u, 0, x);
}
}
}
else //子节点可以参加也可以不参加
{
for (int i = 0; i < v[x].size(); i++)
{
int u = v[x][i];
if (u != fa)
{
dp[x][flag] += max(dfs(u, 1, x), dfs(u, 0, x));
}
}
}
return dp[x][flag];
}
int main()
{
while (~scanf("%d", &n))
{
for (int i = 0; i < maxn; i++)
v[i].clear();
memset(w, 0, sizeof(w));
memset(dp, -1, sizeof(dp));
for (int i = 1; i <= n; i++)
{
scanf("%d", &w[i]);
}
int a, b;
while (scanf("%d %d", &a, &b) && a && b)
{
v[a].push_back(b);
v[b].push_back(a);
}
int ans=max(dfs(1, 0, -1),dfs(1, 1, -1));
printf("%d\n", ans);
}
return 0;
}