Bobjoehi

DWOJ1457

Sep 19th, 2020
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.42 KB | None | 0 0
  1. import java.util.*;
  2. import java.io.*;
  3. public class DWOJ1457 {
  4.    
  5.     static ArrayList<LinkedList<Integer>> adj = new ArrayList<LinkedList<Integer>>();
  6.     static int[] coins;
  7.     static boolean[] visited;
  8.    
  9.     static int find(int node, boolean pickedLast, int parent) {
  10.  
  11.        
  12.         int solution1 = 0;
  13.         for(int i : adj.get(node)) {
  14.             if(i != parent) {
  15.                 solution1 += find(i, false, node);
  16.             }
  17.         }
  18.        
  19.         if(pickedLast) {
  20.             return solution1;
  21.         }
  22.        
  23.         int solution2 = coins[node];
  24.         for(int i : adj.get(node)) {
  25.             if(i != parent) {
  26.                 solution2 += find(i, true, node);
  27.             }
  28.         }
  29.         return Math.max(solution1, solution2);
  30.     }
  31.    
  32.     public static void main(String[] args) throws IOException{
  33.         readLine();
  34.         int n = nextInt();
  35.        
  36.         for(int i = 0; i <= n; i ++) {
  37.             adj.add(new LinkedList<Integer>());
  38.         }
  39.         coins = new int[n + 1];
  40.        
  41.         for(int i = 0; i < n - 1; i ++) {
  42.             readLine();
  43.             int a = nextInt();
  44.             int b = nextInt();
  45.             adj.get(a).add(b);
  46.             adj.get(b).add(a);
  47.         }
  48.         readLine();
  49.         for(int i = 1; i <= n; i ++) {
  50.             coins[i] = nextInt();
  51.         }
  52.        
  53.         visited = new boolean[n + 1];
  54.        
  55.         System.out.println(find(1, false, 0));
  56.     }
  57.     static BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
  58.     static StringTokenizer st;
  59.     static void readLine() throws IOException{
  60.         st = new StringTokenizer(in.readLine());
  61.     }
  62.     static int nextInt() {
  63.         return Integer.parseInt(st.nextToken());
  64.     }
  65. }
  66.  
Advertisement
Add Comment
Please, Sign In to add comment