蓝桥杯 2015年 第六届 生命之树(JAVA)

蓝桥杯 2015年 第六届 生命之树(JAVA)

  • 无根树转有根树
package provincial_2015B;

import java.util.ArrayList;
import java.util.Scanner;

public class Ten {
    private static int[] weight;
    private static long[] total;
    private static ArrayList<ArrayList<Integer>> graph;
    private static long ans;
    
    public static void dfs(int root, int father) {
        
        for(int i = 0; i < graph.get(root).size(); i++) {
            int cur = graph.get(root).get(i);
            if(cur==father) continue;
            dfs(cur, root);
            if(total[cur]>0)
                total[root]+=total[cur];
        }
        
        if(total[root]>ans) ans=total[root];
    }
    
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        int n = scan.nextInt();
        weight = new int[n+1];
        total = new long[n+1];
        for(int i = 1; i < n+1; i++) {
            int a = scan.nextInt();
            weight[i] = a;
            total[i] = a;
        }
        graph = new ArrayList<ArrayList<Integer>>();
        for(int i = 0; i < n+1; i++)
            graph.add(new ArrayList<Integer>());
        for(int i = 0; i < n-1; i++) {
            int u = scan.nextInt();
            int v = scan.nextInt();
            graph.get(u).add(v);
            graph.get(v).add(u);
        }
        dfs(1, 0);
        System.out.println(ans);
    }
}

猜你喜欢

转载自www.cnblogs.com/fromneptune/p/12456087.html