P1352 没有上司的舞会
链接:https://www.luogu.com.cn/problem/P1352
树形dp板子,感觉很巧妙,利用01表示是否取
代码:
#include<iostream>
#include<vector>
#include<algorithm>
#include<math.h>
#include<sstream>
#include<string>
#include<string.h>
#include<iomanip>
#include<stdlib.h>
#include<map>
#include<queue>
#include<cmath>
#include<limits.h>
#include<climits>
#include<fstream>
#include<set>
typedef long long ll;
using namespace std;
const int N = 1e4;
int val[N];
vector<int>G[N];
int fa[N], dp[N][2];
void dfs(int u)
{
dp[u][0] = 0;
dp[u][1] = val[u];
for (int i = 0; i < G[u].size(); i++)
{
int v = G[u][i];
dfs(v);
dp[u][1] += dp[v][0];
dp[u][0] += max(dp[v][0], dp[v][1]);
}
}
int main()
{
ios::sync_with_stdio(false); cin.tie(0), cout.tie(0);
int n; cin >> n;
for (int i = 1; i <= n; i++)cin >> val[i];
for (int i = 1; i < n; i++)
{
int u, v; cin >> u >> v;
G[v].push_back(u);
fa[u] = v;
}
int t = 1;
while (fa[t])t = fa[t];
dfs(t);
cout << max(dp[t][0], dp[t][1]);
return 0;
}