|
| 1 | +package org.example._23week; |
| 2 | + |
| 3 | +import java.io.BufferedReader; |
| 4 | +import java.io.IOException; |
| 5 | +import java.io.InputStreamReader; |
| 6 | +import java.util.ArrayList; |
| 7 | +import java.util.List; |
| 8 | +import java.util.StringTokenizer; |
| 9 | + |
| 10 | +public class GreatTown { |
| 11 | + |
| 12 | + private static final BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); |
| 13 | + private static List<Integer>[] graph; |
| 14 | + private static boolean[] visited; |
| 15 | + private static int[][] dp; |
| 16 | + private static int[] towns; |
| 17 | + private static final int GREAT = 0; |
| 18 | + private static final int NOT_GREAT = 1; |
| 19 | + |
| 20 | + public static void main(String[] args) throws IOException { |
| 21 | + final int townCount = Integer.parseInt(br.readLine()) + 1; |
| 22 | + |
| 23 | + dp = new int[townCount][2]; |
| 24 | + visited = new boolean[townCount]; |
| 25 | + graph = new ArrayList[townCount]; |
| 26 | + for (int i = 0; i < townCount; i++) { |
| 27 | + graph[i] = new ArrayList<>(); |
| 28 | + } |
| 29 | + |
| 30 | + towns = new int[townCount]; |
| 31 | + StringTokenizer st = new StringTokenizer(br.readLine()); |
| 32 | + for (int i = 1; i < townCount; i++) { |
| 33 | + towns[i] = Integer.parseInt(st.nextToken()); |
| 34 | + } |
| 35 | + |
| 36 | + for (int i = 0; i < townCount - 2; i++) { |
| 37 | + st = new StringTokenizer(br.readLine()); |
| 38 | + final int town1 = Integer.parseInt(st.nextToken()); |
| 39 | + final int town2 = Integer.parseInt(st.nextToken()); |
| 40 | + |
| 41 | + graph[town1].add(town2); |
| 42 | + graph[town2].add(town1); |
| 43 | + } |
| 44 | + |
| 45 | + dfs(1); |
| 46 | + System.out.println(Math.max(dp[1][GREAT], dp[1][NOT_GREAT])); |
| 47 | + } |
| 48 | + |
| 49 | + private static void dfs(int vertex) { |
| 50 | + dp[vertex][GREAT] = towns[vertex]; |
| 51 | + dp[vertex][NOT_GREAT] = 0; |
| 52 | + visited[vertex] = true; |
| 53 | + |
| 54 | + for (final Integer adjacent : graph[vertex]) { |
| 55 | + if (visited[adjacent]) { |
| 56 | + continue; |
| 57 | + } |
| 58 | + |
| 59 | + dfs(adjacent); |
| 60 | + dp[vertex][GREAT] += dp[adjacent][NOT_GREAT]; |
| 61 | + dp[vertex][NOT_GREAT] += Math.max(dp[adjacent][GREAT], dp[adjacent][NOT_GREAT]); |
| 62 | + } |
| 63 | + } |
| 64 | +} |
0 commit comments