题目链接:没有上司的舞会
思路
题解
#include <bits/stdc++.h>
using namespace std;
#define ll long long
const int N = 1e5 + 10;
int dp[N][2], happy[N], subordinate[N], cnt, head[N], nex[N], edge[N];
// 链式向前星存储边
void add(int x, int y) {
nex[++cnt] = head[x];
head[x] = cnt;
edge[cnt] = y;
}
// 树形dp
void dfs(int x) {
dp[x][0] = 0;
dp[x][1] = happy[x];
for (int i = head[x]; i; i = nex[i]) {
int to = edge[i];
dfs(to);
dp[to][1] += dp[to][0];
dp[to][0] += max(dp[to][0], dp[to][1]);
}
}
int main() {
int n, l, k;
cin >> n;
for (int i = 1; i <= n; i++) {
cin >> happy[i];
}
for (int i = 1; i < n; i++) {
cin >> l >> k;
add(k, l);
subordinate[l] = true;
}
int root;
for (int i = 1; i <= n; i++) {
if (subordinate[i] == false) {
root = i;
break;
}
}
dfs(root);
cout << max(dp[root][0], dp[root][1]);
return 0;
}
标签:舞会,洛谷,int,head,nex,cnt,P1352,dp,happy
From: https://www.cnblogs.com/againss/p/18245503