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. static int[] dp;
  11. static int[] dp1;
  12.  
  13. public static void findSum(int node, ArrayList<Integer>[] adj, int[] vis, int[] parent){
  14. vis[node] = 1;
  15. int cnt = 0;
  16.  
  17. for(int ch: adj[node]){
  18. if(vis[ch] == 0){
  19. parent[ch] = node;
  20. findSum(ch, adj, vis, parent);
  21. cnt += dp[ch];
  22. }
  23. }
  24. dp[node] = cnt + 1;
  25.  
  26. int sum = 0;
  27. for(int ch: adj[node]){
  28. if(vis[ch] != parent[node]){
  29. sum += dp1[ch] + 1 + dp[ch];
  30. }
  31. }
  32. dp1[node] = sum;
  33. }
  34. public static void main (String[] args) throws java.lang.Exception
  35. {
  36. // your code goes here
  37. Scanner sc = new Scanner(System.in);
  38. int n = sc.nextInt();
  39. ArrayList<Integer>[] adj = new ArrayList[n];
  40. for(int i=0;i<n;i++){
  41. adj[i] = new ArrayList<>();
  42. }
  43.  
  44. for(int i=0;i<n-1;i++){
  45. int x = sc.nextInt();
  46. int y = sc.nextInt();
  47. adj[x].add(y);
  48. adj[y].add(x);
  49. }
  50.  
  51. dp = new int[n];
  52. dp1 = new int[n];
  53. int[] vis = new int[n];
  54. int[] parent = new int[n];
  55. Arrays.fill(parent, -1);
  56. findSum(0,adj,vis,parent);
  57. for(int i=0;i<n;i++){
  58. System.out.println("node " + i +" " + dp1[i]);
  59. }
  60. }
  61. }
Success #stdin #stdout 0.19s 58924KB
stdin
10
0 1
0 2
0 3
1 4
1 5
2 6
3 7
3 8
4 9
stdout
node 0 29
node 1 6
node 2 4
node 3 7
node 4 0
node 5 0
node 6 1
node 7 1
node 8 1
node 9 1