天天看點

Anniversary party(樹形dp第一步)

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      

題目大意:

       學校要舉辦周年紀念日,每個人都有一個歡樂度,但是見到自己的直接上司的時候瞬間就不歡樂了,So,上司去我不去,上司不去我再去,這樣才能愉快的玩耍,然後求最大的歡樂度。

解題思路:

       給出一個關系圖,把它轉化成一個樹(小白書上面有,無根樹轉有根樹),然後求出遞推方程

                                  dp[i][0] += max(dp[j][0] , dp[j][1]);  i為上司,j為下級                dp[ i ][ 1 ] += dp[ j ][ 0 ];  dp[i][0]表示i不去,dp[i][1]表示i去。

一次周遊求最優解就可以了。

代碼如下:

#include<iostream>
#include<cstdio>
#include<map>
#include<math.h>
#include<cstring>
#include<vector>
#include<algorithm>
using namespace std;

int pre[6010];
vector<int> G[6010]; // 動态存儲鄰接矩陣
int dp[6010][2], vis[6010], n;

void dfs(int u, int father)
{
    int d = G[u].size();
    for(int i = 0; i < d; i++)
    {
        int v = G[u][i];
        if(v != father)
        {
            dfs(v, pre[v] = u);
        }
    }
}

void d(int t)
{
    vis[t] = 1;// 标記已被通路
    for(int i = 1; i <= n; i++)
    {
        if(pre[i] == t && !vis[i])
        {
            d(i);//當周遊到葉子,求最優解
            dp[t][0] += max(dp[i][0], dp[i][1]);
            dp[t][1] += dp[i][0];
        }
    }
}

int main()
{
    int i, u, v;
    while(scanf("%d",&n) != EOF)
    {
        memset(dp, 0, sizeof(dp));
        for(i = 1; i <= n; i++)
            scanf("%d",&dp[i][1]);
        while(scanf("%d%d",&u,&v) && (u + v))
        {
            G[u].push_back(v);
            G[v].push_back(u);
        }
        memset(pre, -1, sizeof(pre));//設定初始都指向-1位父親結點
        dfs(1,-1);
        memset(vis, 0, sizeof(vis));
        d(1);
        printf("%d\n",max(dp[1][0], dp[1][1]));
    }
    return 0;
}