fork download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.lang.*;
  5. import java.io.*;
  6.  
  7. /* Name of the class has to be "Main" only if the class is public. */
  8. class Ideone
  9. {
  10. public static void main (String[] args) throws java.lang.Exception
  11. {
  12. Scanner sc = new Scanner(System.in);
  13.  
  14. int n = sc.nextInt(); // number of nodes
  15. List<Integer>[] child = new List[n + 1];
  16. for (int i = 1; i <= n; i++) {
  17. child[i] = new ArrayList<>();
  18. }
  19.  
  20. // Read n-1 edges
  21. for (int i = 1; i < n; i++) {
  22. int u = sc.nextInt();
  23. int v = sc.nextInt();
  24. child[u].add(v);
  25. child[v].add(u);
  26. }
  27. int [] value = new int[n+1];
  28.  
  29. for(int i = 1;i <= n;i++){
  30. value[i] = sc.nextInt();
  31. }
  32.  
  33. int[] used = new int[n + 1];
  34. int[] parent = new int[n + 1];
  35. int[] sum = new int[n + 1];
  36.  
  37.  
  38. dfs(child, 1,value,used, parent,sum);
  39. }
  40.  
  41. public static void dfs(List<Integer>[] child, int node,int [] value,int[] used, int[] parent, int[] sum) {
  42. used[node] = 1;
  43.  
  44. for (int v : child[node]) {
  45. if (used[v] == 0) {
  46. parent[v] = node;
  47. dfs(child, v,value,used, parent,sum);
  48. }
  49. }
  50.  
  51. int subSum = 0;
  52. for (int v : child[node]) {
  53. if (v == parent[node]) continue;
  54. subSum += sum[v];
  55. }
  56.  
  57. sum[node] = value[node] + subSum;
  58. System.out.println(sum[node]);
  59. }
  60. }
Success #stdin #stdout 0.18s 54600KB
stdin
5
1 2
1 3
3 4
3 5
1 2 3 4 5
stdout
2
4
5
12
15