Source code for submission s770

Fr.java

  1. import java.util.ArrayList;
  2. import java.util.Iterator;
  3. import java.util.LinkedList;
  4. import java.util.Scanner;
  5.  
  6.  
  7. public class Fr {
  8.  
  9. public static void main(String[] args) {
  10. Scanner sc = new Scanner(System.in);
  11.  
  12. int n;
  13. int main;
  14. ArrayList<Node> nodes;
  15.  
  16. int a;
  17. int b;
  18. int v;
  19. Node tempNode;
  20. Node father;
  21. while(sc.hasNextInt()){
  22. a = 0;
  23. b = 0;
  24.  
  25. n = sc.nextInt();
  26. nodes = new ArrayList<Node>(n+1);
  27. for (int i = 0; i < n+1; i++) {
  28. nodes.add(null);
  29. }
  30. // System.out.println(nodes.size());
  31. main = sc.nextInt();
  32. nodes.add(main, new Node(main, Integer.MAX_VALUE));
  33.  
  34. for (int i = 0; i < n-1; i++) {
  35. a = sc.nextInt();
  36. b = sc.nextInt();
  37. v = sc.nextInt();
  38.  
  39. father = nodes.get(a);
  40. if (father == null){
  41. tempNode = new Node(a, v);
  42. nodes.set(a, tempNode);
  43.  
  44. father = nodes.get(b);
  45. father.addChild(tempNode);
  46. }else{
  47. tempNode = new Node(b, v);
  48. nodes.set(b, tempNode);
  49.  
  50. father.addChild(tempNode);
  51. }
  52. }
  53.  
  54. System.out.println(getNodeValue(nodes.get(main)));
  55. }
  56. sc.close();
  57. }
  58.  
  59.  
  60. static int getNodeValue(Node node){
  61. if (node.child.size() == 0){
  62. return node.value;
  63. }
  64.  
  65. int sumV = 0;
  66. for (Node n : node.child) {
  67. sumV += getNodeValue(n);
  68. }
  69.  
  70. if (node.value > sumV){
  71. node.value = sumV;
  72. return node.value;
  73. }
  74. return node.value;
  75. }
  76. }
  77.  
  78. class Node{
  79. int id;
  80. int value;
  81. LinkedList<Node> child;
  82. Node ancestor;
  83.  
  84. public Node(int id, int value) {
  85. super();
  86. this.id = id;
  87. this.value = value;
  88.  
  89. child = new LinkedList<Node>();
  90. // this.ancestor = ancestor;
  91. }
  92.  
  93. void addChild(Node node){
  94. this.child.add(node);
  95. }
  96.  
  97. }