Anniversary party_poj2342_树形dp

来源:互联网 发布:美国非农数据11月预测 编辑:程序博客网 时间:2024/06/02 00:27

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.

Analysis


n年前的坑现在才来填真是作死
f[i][1]表示i员工参加的最大值
那么f[i][0]就是i员工不参加的最大值
容易得到
f[i][0]=max(f[j][0],f[j][1])
f[i][1]=w[i]+f[j][0]
其中i是j的上司
边界就是叶节点,把没有老板的老板全部连向0
答案是max(f[0][0],f[0][1])

Code


#include <stdio.h>using namespace std;#define max(x,y) x>y?x:y#define maxn 6000struct edge{int y,next;}e[maxn+1];int ind[maxn+1],ls[maxn+1],c[maxn+1],f[maxn+1][2],maxE=0;bool vis[maxn+1];void add(int x,int y){    e[++maxE]=(edge){y,ls[x]};    ls[x]=maxE;    ind[y]++;}void dfs(int root){    if (vis[root])        return;    vis[root]=true;    if (!ls[root])    {        f[root][1]=c[root];        return;    }    for (int i=ls[root];i;i=e[i].next)    {        dfs(e[i].y);        f[root][1]+=f[e[i].y][0];        f[root][0]+=max(f[e[i].y][0],f[e[i].y][1]);    }    f[root][1]+=c[root];}int main(){    int n;    scanf("%d",&n);    for (int i=1;i<=n;i++)        scanf("%d",&c[i]);    int x,y;    while (scanf("%d%d",&y,&x)&&x&&y)        add(x,y);    for (int i=1;i<=n;i++)        if (!ind[i])            add(0,i);    dfs(0);    printf("%d\n",max(f[0][0],f[0][1]));    return 0;}
0 0