天天看點

POJ 2342Anniversary party(樹形dp)

Anniversary party

Time Limit: 1000MS Memory Limit: 65536K
Total Submissions: 8526 Accepted: 4909

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 想法:

題意:話說一個公司的一些然要去參加一個party,每個人有一個愉悅值,而如果某個人的直接上司在場的話會非常掃興,是以避免這樣的安排,問給出n個人,每個人的愉悅值以及他們的上司所屬關系,問你讓那些人去可以讓總的愉悅值最大,并求出這個值。

 分析:樹形dp入門題目,這個公司的人事關系可以根據給出的資料得到一個樹,最上面的是最高層,往下依次,我們要做的就是在樹的節點處進行dp。 用dp【i】【0】表示當第i這個人不選,dp【i】【1】表示當第i這個人安排去參加

dp[o][0]+=max(dp[i][0],dp[i][1]);//父節點不選,子節點可選可不選

 dp[o][1]+=dp[i][0];//父節點已選,子節點不能選

代碼: #include <stdio.h>

#include <stdlib.h>

#include <string.h>

#define N 10000

int max(int a,int b)

{

    return a>b?a:b;

}

int dp[N][2];  ///dp[i][0]表示目前i點不選 1表示選

int father[N],vis[N];

int n;

void creat(int o)

{

    vis[o]=1;

    for(int i=1;i<=n;i++)

    {

        if(vis[i]==0 && father[i]==o)

        {

            creat(i);

            dp[o][0]+=max(dp[i][0],dp[i][1]);//父節點不選,子節點可選可不選

            dp[o][1]+=dp[i][0];//父節點已選,子節點不能選

        }

    }

}

int main()

{

    int i;

    while(~scanf("%d",&n))

    {

        memset(vis,0,sizeof(vis));

        memset(father,0,sizeof(father));

        memset(dp,0,sizeof(dp));

        for(i=1; i<=n; i++)

        {

            scanf("%d",&dp[i][1]);

        }

        int f,c,root;

        root = 0;//記錄父結點

        while(scanf("%d %d",&c,&f),c||f)

        {

            father[c] = f;

        }

        creat(root);

        int imax=max(dp[root][0],dp[root][1]);

        printf("%d\n",imax);

    }

    return 0;

}