285. 没有上司的舞会(树形dp)

#include <bits/stdc++.h>
using namespace std;

const int N = 6060;

int h[N], e[N], ne[N],idx;
int w[N], f[N][2];
bool hasF[N];
int n;

void add(int a, int b) {
    e[idx] = b, ne[idx] = h[a], h[a] = idx++;
}

void dfs(int root) {
    int notdo = 0, dodo = w[root];
    for(int i = h[root]; ~i; i = ne[i]) {
        int j = e[i];
        dfs(j);
        notdo += max(f[j][0],f[j][1]);
        dodo += f[j][0];
    }
    f[root][0] = notdo;
    f[root][1] = dodo;
}

int main() {
    scanf("%d",&n);
    for(int i = 1; i <= n; i++) scanf("%d",&w[i]);
    memset(h,-1,sizeof h);
    for(int i = 0; i < n - 1; i++) {
        int a, b;
        scanf("%d%d",&a,&b);
        add(b,a);
        hasF[a] = true;
    }
    int root = 1;
    while(hasF[root]) {
        root++;
    }
    dfs(root);
    printf("%d
",max(f[root][0],f[root][1]));
    return 0;
}
原文地址:https://www.cnblogs.com/yonezu/p/13525900.html