求教第二个用例未通过,以下代码输出是3000
查看原帖
求教第二个用例未通过,以下代码输出是3000
746484
mozhumz楼主2022/7/6 17:28
import java.util.HashMap;
import java.util.List;
import java.util.ArrayList;
import java.util.Scanner;
import java.util.Map;
public class Main{ 
public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int[][] f = new int[n][2];
        int[]h=new int[n];
        for (int i = 0; i < n; i++) {
            // f[i][1] = sc.nextInt();
            h[i]=sc.nextInt();
        }
        boolean[] hasParent = new boolean[n];
        Map<Integer, List<Integer>> childMap = new HashMap<>();
        for (int i = 0; i < n - 1; i++) {
            int l = sc.nextInt() - 1;
            int k = sc.nextInt() - 1;
            if(l<0||k<0){
                            continue;
                        }
            List<Integer> list = childMap.get(k);
            if (list == null || list.isEmpty()) {
                list = new ArrayList<>();
            }
            list.add(l);
            childMap.put(k, list);
            hasParent[l] = true;
        }
        int root = 0;
        for (int i = 0; i < hasParent.length; i++) {
            if (!hasParent[i]) {
                root = i;
                break;
            }
        }
        dfs(root, f, childMap,h);
        System.out.println(Math.max(f[root][1], f[root][0]));
    }

    public static void dfs(int u, int[][] f, Map<Integer, List<Integer>> childMap,int []h) {
        f[u][1]=h[u];
        List<Integer> children = childMap.get(u);
        if (children == null) {
            return;
        }
        for (Integer i : children) {
            dfs(i, f, childMap,h);
            f[u][0] += Math.max(f[i][0], f[i][1]);
            f[u][1] += f[i][0];
        }
    }
}
2022/7/6 17:28
加载中...