Cod sursa(job #3143733)

Utilizator rahulvermaRahul Verma rahulverma Data 1 august 2023 20:30:42
Problema Asmax Scor 100
Compilator java Status done
Runda Arhiva de probleme Marime 1.27 kb
import java.io.*;
import java.util.*;

public class Main {
	public static int n;
	public static int[] arr;
	public static long[] sub;
	public static boolean[] seen;
	public static ArrayList<ArrayList<Integer>> graph = new ArrayList<ArrayList<Integer>>();
	
	public static void main(String[] args) throws IOException {
		BufferedReader br = new BufferedReader(new FileReader("asmax.in"));
		n = Integer.parseInt(br.readLine());
		StringTokenizer st = new StringTokenizer(br.readLine());
		arr = new int[n];
		seen = new boolean[n];
		sub = new long[n];
		for(int i = 0; i < n; i++) {
			arr[i] = Integer.parseInt(st.nextToken());
			graph.add(new ArrayList<Integer>());
		}
		for(int i = 1; i < n; i++) {
			st = new StringTokenizer(br.readLine());
			int v1 = Integer.parseInt(st.nextToken()) - 1;
			int v2 = Integer.parseInt(st.nextToken()) - 1;
			graph.get(v1).add(v2);
			graph.get(v2).add(v1);
		}
		long ans = Long.MIN_VALUE;
		dfs(0);
		for(long v: sub) ans = Math.max(v,  ans);
		PrintWriter pw = new PrintWriter("asmax.out");
		pw.println(ans);
		pw.close();
		
	}
	
	public static void dfs(int node) {
		seen[node] = true;
		sub[node] += arr[node];
		for(int node2: graph.get(node)) {
			if(seen[node2]) continue;
			dfs(node2);
			if(sub[node2] > 0) sub[node] += sub[node2];
		}
	}

}