codevs 1380 沒有上司的舞會 樹形DP

題目描述 Description
Ural大學有N個職員,編號爲1~N。他們有從屬關係,也就是說他們的關係就像一棵以校長爲根的樹,父結點就是子結點的直接上司。每個職員有一個快樂指數。現在有個週年慶宴會,要求與會職員的快樂指數最大。但是,沒有職員願和直接上司一起與會。

輸入描述 Input Description

第一行一個整數N。(1<=N<=6000)
接下來N行,第i+1行表示i號職員的快樂指數Ri。(-128<=Ri<=127)
接下來N-1行,每行輸入一對整數L,K。表示K是L的直接上司。 最後一行輸入0,0。

輸出描述 Output Description

輸出最大的快樂指數。

樣例輸入 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

數據範圍及提示 Data Size & Hint

各個測試點1s

一個樹形DP的題啦!

#include <iostream>
#include <cstdio>
using namespace std;

struct Edge
{
    int f, t;
}es[6010];
int tot = 1, first[6010], nxt[6010], num[6010], fa[6010], dp[6010][5];

void build(int f, int t)
{
    es[++tot] = (Edge){f, t};
    nxt[tot] = first[f];
    first[f] = tot;
}

void dfs(int u)
{
    dp[u][1] += num[u];
    for(int i = first[u]; i; i = nxt[i])
    {
        int v = es[i].t;
        dfs(v);
        dp[u][0] += max(dp[v][0], dp[v][1]);
        dp[u][1] += dp[v][0];
    }
}

int main()
{
    int n;
    scanf("%d", &n);
    for(int i = 1; i <= n; i++)
        scanf("%d", &num[i]), fa[i] = i;
    int f, t;
    for(int i = 1; i <= n; i++)
    {
        scanf("%d%d", &t, &f);
        if(t && f) build(f, t), fa[t] = f;
    }
    int rt;
    for(int i = 1; i <= n; i++)
        if(fa[i] == i) dfs(i), rt = i;  
    printf("%d", max(dp[rt][1], dp[rt][0]));
    return 0;
}
發佈了62 篇原創文章 · 獲贊 4 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章