原题链接:
285. 没有上司的舞会 - AcWing题库
题解:
![](https://i-blog.csdnimg.cn/direct/182f0a2dfb9b4bf18c006b8943396265.png)
代码:
#include<bits/stdc++.h>
using namespace std;
const int N = 6e3 + 10;
int hap[N], has_father[N], f[N][2];
vector<int> v[N];
int n, root = 1;
void dfs(int x) {
f[x][1] = hap[x];
for (auto i : v[x]) {
dfs(i);
f[x][0] += max(f[i][0], f[i][1]);
f[x][1] += f[i][0];
}
}
int main() {
cin >> n;
for (int i = 1;i <= n;i++) cin >> hap[i];
for (int i = 1;i <= n - 1;i++) {
int a, b;cin >> a >> b;
v[b].push_back(a);
has_father[a] = 1;
}
while (has_father[root]) root++;
dfs(root);
cout << max(f[root][0], f[root][1]);
}