洛谷 P1352 沒有上司的舞會
Description
- 某大學有N個職員,編號為1~N。他們之間有從屬關系,也就是說他們的關系就像一棵以校長為根的樹,父結點就是子結點的直接上司。現在有個周年慶宴會,宴會每邀請來一個職員都會增加一定的快樂指數Ri,但是呢,如果某個職員的上司來參加舞會了,那么這個職員就無論如何也不肯來參加舞會了。所以,請你編程計算,邀請哪些職員可以使快樂指數最大,求最大的快樂指數。
Input
第一行一個整數N。(1<=N<=6000)
接下來N行,第i+1行表示i號職員的快樂指數Ri。(-128<=Ri<=127)
接下來N-1行,每行輸入一對整數L,K。表示K是L的直接上司。
最后一行輸入0 0
Output
- 輸出最大的快樂指數。
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
題解:
- 簡單的樹形dp
#include <iostream>
#include <cstdio>
#define N 6005
using namespace std;struct E {int next, to;} e[N];
int n, m, num, root;
int a[N], in[N], h[N];
int dp[N][2];void add(int u, int v)
{e[++num].next = h[u];e[num].to = v;h[u] = num;
}void dfs(int x, int fat)
{for(int i = h[x]; i != 0; i = e[i].next)if(e[i].to != fat) dfs(e[i].to, x);for(int i = h[x]; i != 0; i = e[i].next)if(e[i].to != fat)dp[x][1] += dp[e[i].to][0],dp[x][0] += max(dp[e[i].to][0], dp[e[i].to][1]);dp[x][1] += a[x];
}int main()
{cin >> n;for(int i = 1; i <= n; i++) cin >> a[i];for(int i = 1; i < n; i++){int u, v; cin >> u >> v;add(v, u), in[u]++;}for(int i = 1; i <= n; i++)if(!in[i]) {root = i; break;}dfs(root, 0);cout << max(dp[root][0], dp[root][1]);return 0;
}