错误数据#2,本地编译能过
代码:
#include <iostream>
using namespace std;
const int N = 6010;
int n;
int w[N], f[N][2 /*0表示不选该节点,1表示选该节点*/];
int son[N /*爹的编号*/][N /*第几个儿子*/] /*值是儿子的编号*/;
int NumberOfSons[N];
int fa[N /*儿子的编号*/] /*爹的编号*/;
void dfs_dp(int node)//dfs遍历,回溯dp
{
f[node][1] = w[node];
for (int i = 1; i <= NumberOfSons[node]; i++)
{
int SonNode = son[node][i];
dfs_dp(SonNode);
f[node][0] += max(f[SonNode][0], f[SonNode][1]);
f[node][1] += f[SonNode][0];
}
return;
}
int main()
{
cin >> n;
for (int i = 1; i <= n; i++)
cin >> w[i];
for (int i = 1; i < n; i++)
{
int x, y;
cin >> x >> y;
NumberOfSons[y]++;
son[y][NumberOfSons[y]] = x;
fa[x] = y;
}
// 寻找根节点
int root = 1;
while (fa[root])
root = fa[root];
dfs_dp(root);
cout << max(f[root][0], f[root][1]);
return 0;
}