没有上司的舞会.java 1.4 KB
Newer Older
qq_36480062's avatar
qq_36480062 已提交
1
package dp.树形dp;
qq_36480062's avatar
c  
qq_36480062 已提交
2 3 4 5 6 7 8 9

import java.util.Scanner;

public class 没有上司的舞会 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        n = sc.nextInt();
        for (int i = 1; i <= n; i++) {
qq_36480062's avatar
c  
qq_36480062 已提交
10
            f[i][1] = sc.nextInt();
qq_36480062's avatar
c  
qq_36480062 已提交
11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
        }
        int a, b;
        for (int i = 0; i < n - 1; i++) {
            a = sc.nextInt();
            b = sc.nextInt();
            add(b, a);
            hasf[a] = true;
        }
        int root = 1;
        while (hasf[root]) root++;
        dfs(root);
        System.out.println(Math.max(f[root][1], f[root][0]));
    }

    private static void dfs(int u) {
qq_36480062's avatar
c  
qq_36480062 已提交
26
       // f[u][1] = happy[u];//选择了u就加上u的幸福指数
qq_36480062's avatar
c  
qq_36480062 已提交
27 28 29
        for (int i = he[u]; i != 0; i = ne[i]) {
            int j = e[i];
            dfs(j);
qq_36480062's avatar
c  
qq_36480062 已提交
30
            f[u][1] += f[j][0];//选当前节点,但不选子节点
qq_36480062's avatar
c  
qq_36480062 已提交
31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
            f[u][0] += Math.max(f[j][0], f[j][1]);
            //不选当前节点,是选还是不选子节点
        }
    }

    static int[][] f = new int[6010][6010];

    static void add(int u, int v) {
        e[cnt] = v;
        ne[cnt] = he[u];
        he[u] = cnt++;
    }

    static int n, cnt = 1;
    static int[] he = new int[6010];
    static int[] ne = new int[6010];
    static int[] e = new int[6010];
    static int[] happy = new int[6010];
    static boolean[] hasf = new boolean[6010];

}