Source code for submission s945

Main.java

  1.  
  2. import java.util.HashMap;
  3. import java.util.Map;
  4. import java.util.Scanner;
  5.  
  6. /**
  7.  *
  8.  * @author cteam049
  9.  */
  10. public class Main {
  11.  
  12. static class Node {
  13. Map<Integer, Node> sucs = new HashMap<Integer, Main.Node>();
  14. int value;
  15. int force;
  16.  
  17. public Node(int value) {
  18. this.value = value;
  19. }
  20. }
  21.  
  22. private static boolean appendNode(Node node, int i1, int i2, int i3) {
  23. if (node.value == i1) {
  24. Node n = new Node(i2);
  25. n.force = i3;
  26. node.sucs.put(i2, n);
  27. return true;
  28. } else if (node.value == i2) {
  29. Node n = new Node(i1);
  30. n.force = i3;
  31. node.sucs.put(i1, n);
  32. return true;
  33. } else if (node.sucs.containsKey(i1)) {
  34. return appendNode(node.sucs.get(i1), i1, i2, i3);
  35. } else if (node.sucs.containsKey(i2)) {
  36. return appendNode(node.sucs.get(i2), i1, i2, i3);
  37. } else {
  38. for (Node tmp : node.sucs.values()) {
  39. if (appendNode(tmp, i1, i2, i3)) return true;
  40. }
  41. }
  42. return false;
  43. }
  44.  
  45.  
  46. private static void preorder(Node node) {
  47. System.out.println(node.value);
  48. for (Node n : node.sucs.values()) {
  49. preorder(n);
  50. }
  51.  
  52. }
  53.  
  54. private static int solve(Node node) {
  55. if (node.sucs.isEmpty()) {
  56. return node.force;
  57. }
  58. int sum = 0;
  59. for (Node n : node.sucs.values()) {
  60. sum += solve(n);
  61. }
  62. if (sum < node.force) {
  63. return sum;
  64. }
  65. return node.force;
  66. }
  67.  
  68. public static void main(String[] args) {
  69. Scanner sc = new Scanner(System.in);
  70. String line = null;
  71. int n, c;
  72. while (sc.hasNext()) {
  73. n = sc.nextInt();
  74. c = sc.nextInt();
  75. Node n1 = new Node(c);
  76. n1.force = Integer.MAX_VALUE;
  77.  
  78. for (int i=0 ; i<n-1 ; i++) {
  79. int i1 = sc.nextInt();
  80. int i2 = sc.nextInt();
  81. int i3 = sc.nextInt();
  82. appendNode(n1, i1, i2, i3);
  83. }
  84.  
  85. // preorder(n1);
  86. System.out.println(solve(n1));
  87. }
  88. }
  89.  
  90. }
  91.