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