Source code for submission s655

Main.java

  1. /*
  2.  * To change this template, choose Tools | Templates
  3.  * and open the template in the editor.
  4.  */
  5.  
  6. import java.io.*;
  7. import java.util.*;
  8.  
  9.  
  10. /**
  11.  *
  12.  * @author cteam028
  13.  */
  14. public class Main {
  15.  
  16. /**
  17.   * @param args the command line arguments
  18.   */
  19. static Node[] nodea;
  20.  
  21. public static void main(String[] args) throws Exception {
  22. String line;
  23. while((line = br.readLine()) != null) {
  24. int nodes, root;
  25. String a[] = line.split(" ");
  26. nodes = Integer.parseInt(a[0]);
  27. root = Integer.parseInt(a[a.length-1]);
  28.  
  29. nodea = new Node[nodes+1];
  30.  
  31. for(int i = 0 ; i <= nodes; i++) {
  32. nodea[i] = new Node();
  33. }
  34. for(int i = 0; i < nodes-1;i++) {
  35. int b[] = new int[3];
  36. parseIntArr(br.readLine().toCharArray(), b);
  37.  
  38. nodea[b[0]].childs.add(new Edge(b[1], b[2]));
  39. nodea[b[1]].childs.add(new Edge(b[0], b[2]));
  40. }
  41.  
  42. System.out.println(compute(root));
  43. }
  44. }
  45.  
  46. static int compute(int node) {
  47. nodea[node].used = true;
  48. int sum = 0;
  49. boolean found = false;
  50. for(Edge e : nodea[node].childs) {
  51. if(nodea[e.endNode].used) continue;
  52. else {
  53. sum += Math.min(compute(e.endNode), e.weight);
  54. found = true;
  55. }
  56. }
  57.  
  58. if(found) return sum;
  59. else return Integer.MAX_VALUE;
  60. }
  61.  
  62. public static void parseIntArr(char[] arr, int[] target)
  63. {
  64. int i = 0;
  65. int acc = -1;
  66.  
  67. for(char ch :arr)
  68. {
  69. if(ch == ' ')
  70. {
  71. if(acc!= -1)
  72. {
  73. target[i++] = acc;
  74. acc = -1;
  75. }
  76. }
  77. else if(acc == -1)
  78. acc = ch - '0';
  79. else
  80. acc = acc * 10 + (ch - '0');
  81. }
  82. if(acc != -1)
  83. target[i] = acc;
  84. }
  85.  
  86. }
  87.  
  88. class Node {
  89. LinkedList<Edge> childs = new LinkedList<Edge>();
  90. boolean used = false;
  91. }
  92. class Edge {
  93. int endNode, weight;
  94. public Edge(int a, int b) {
  95. endNode = a;
  96. weight = b;
  97. }
  98. }
  99.