没有上司的舞会
链接 : https://www.acwing.com/problem/content/287/
状态表示
- \(f[u][0] : 表示不要 u 点的最大价值\)
- \(f[u][1] : 表示要 u 点的最大价值\)
状态计算
\( \begin{aligned} f[u][1] &+= \sum f[j][u]\\ f[u][0] &+= \sum max(f[j][0], f[j][1]) \end{aligned} \)
代码
#include <bits/stdc++.h>
using namespace std;
#define IO ios::sync_with_stdio(false);cin.tie(0); cout.tie(0)
inline int lowbit(int x) { return x & (-x); }
#define ll long long
#define pb push_back
#define PII pair<int, int>
#define fi first
#define se second
#define inf 0x3f3f3f3f
const int N = 6010;
int ne[N], h[N], e[N], idx;
int w[N], f[N][2];
bool has_fa[N];
void add(int a, int b) {
ne[idx] = h[a], e[idx] = b, h[a] = idx++;
}
void dfs(int u) {
f[u][1] = w[u];
for (int i = h[u]; ~i; i = ne[i]) {
int j = e[i];
dfs(j);
f[u][1] += f[j][0];
f[u][0] += max(f[j][0], f[j][1]);
}
}
int main() {
IO;
memset(h, -1, sizeof h);
int n;
cin >> n;
for (int i = 1; i <= n; ++i) cin >> w[i];
for (int i = 0; i < n - 1; ++i) {
int a, b;
cin >> a >> b;
add(b, a);
has_fa[a] = true;
}
int root = 1;
while (has_fa[root]) ++root;
dfs(root);
cout << max(f[root][0], f[root][1]) << '\n';
return 0;
}