Source code for submission s752

Main.java

  1.  
  2. import java.io.BufferedReader;
  3. import java.io.InputStreamReader;
  4. import java.util.StringTokenizer;
  5.  
  6. public class Main {
  7.  
  8. protected int nodesCnt;
  9. protected int centralNode;
  10. protected int[][] edges;
  11. protected int[][] edgesPrice;
  12. protected int[] edgesCnt;
  13.  
  14. public static void main(String[] args) throws Exception {
  15. Main p = new Main();
  16. p.run();
  17. }
  18.  
  19. protected void run() throws Exception {
  20. while (input.ready()) {
  21. this.nodesCnt = this.nextInt();
  22. this.centralNode = this.nextInt();
  23.  
  24. edges = new int[nodesCnt + 1][nodesCnt];
  25. edgesPrice = new int[nodesCnt + 1][nodesCnt];
  26. edgesCnt = new int[nodesCnt + 1];
  27.  
  28. for (int i = 0; i < this.nodesCnt - 1; i++) {
  29. int b = this.nextInt();
  30. int e = this.nextInt();
  31. int price = this.nextInt();
  32. edges[b][edgesCnt[b]] = e;
  33. edges[e][edgesCnt[e]] = b;
  34. edgesPrice[b][edgesCnt[b]] = price;
  35. edgesPrice[e][edgesCnt[e]] = price;
  36. edgesCnt[b]++;
  37. edgesCnt[e]++;
  38. }
  39. System.out.println(getPrice(centralNode, -10));
  40. }
  41. }
  42.  
  43. protected int getPrice(int node, int parent) {
  44. int closeMePrice = 0;
  45. int closeChildrenPrice = 0;
  46. for (int i = 0; i < edgesCnt[node]; i++) {
  47. if (edges[node][i] != parent) {
  48. closeMePrice += edgesPrice[node][i];
  49. closeChildrenPrice += getPrice(edges[node][i], node);
  50. }
  51. }
  52. if (closeChildrenPrice == 0) {
  53. return closeMePrice;
  54. }
  55. return Math.min(closeMePrice, closeChildrenPrice);
  56. }
  57.  
  58.  
  59. public String nextToken() throws Exception {
  60. while (!st.hasMoreTokens()) {
  61. st = new StringTokenizer(input.readLine());
  62. }
  63. return st.nextToken();
  64. }
  65.  
  66. public int nextInt() throws Exception {
  67. return Integer.parseInt(nextToken());
  68. }
  69.  
  70. public String nextLine() throws Exception {
  71. return input.readLine();
  72. }
  73.  
  74. }
  75.