Luogu P1352 没有上司的舞会

题目描述

https://www.luogu.com.cn/problem/P1352

树形dp入门题

Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#include <iostream>
#include <cstdio>
#include <cstring>
#define maxn 6010
using namespace std;

int n, a[maxn];

struct Edge {
int to, next;
} e[maxn * 2]; int c1, head[maxn];
inline void add_edge(int u, int v) {
e[c1].to = v; e[c1].next = head[u]; head[u] = c1++;
}

int f[maxn][2];
void dfs(int u, int fa) {
f[u][1] = a[u];
for (int i = head[u]; ~i; i = e[i].next) {
int v = e[i].to; if (v == fa) continue;
dfs(v, u);
f[u][1] += f[v][0];
f[u][0] += max(f[v][0], f[v][1]);
}
}

int main() { memset(head, -1, sizeof head);
cin >> n;
for (int i = 1; i <= n; ++i) cin >> a[i];
for (int i = 1; i < n; ++i) {
int x, y; cin >> x >> y;
add_edge(x, y); add_edge(y, x);
}
dfs(1, 0);
cout << max(f[1][0], f[1][1]);
return 0;
}