Source code for submission s629

Fr.java

  1. /*
  2.  * To change this template, choose Tools | Templates
  3.  * and open the template in the editor.
  4.  */
  5. package basic;
  6.  
  7. import java.io.BufferedReader;
  8. import java.io.InputStreamReader;
  9. import java.util.Arrays;
  10. import java.util.HashMap;
  11. import java.util.Map;
  12. import java.util.Scanner;
  13. import java.util.StringTokenizer;
  14.  
  15. /**
  16.  *
  17.  * @author cteam043
  18.  */
  19. public class Fr {
  20.  
  21. static final double EPS = 1E-7;
  22. Scanner sc = new Scanner(System.in);
  23.  
  24. String nextToken() throws Exception {
  25. while (!st.hasMoreTokens()) {
  26. st = new StringTokenizer(input.readLine());
  27. }
  28. return st.nextToken();
  29. }
  30.  
  31. int nextInt() throws Exception {
  32. return Integer.parseInt(nextToken());
  33. }
  34. int[][] matrix = new int[1001][1001];
  35. int n, root;
  36.  
  37. /**
  38.   * @param args the command line arguments
  39.   */
  40. public static void main(String[] args) throws Exception {
  41. new Fr().solve();
  42. }
  43.  
  44. public void solve() throws Exception {
  45. int u, v, w;
  46. while (sc.hasNextInt()) { // nextToken eof?
  47. n = sc.nextInt();
  48. root = sc.nextInt();
  49. for(int i = 0; i <= n; i++){
  50. for(int j = 0; j <= n; j++){
  51. matrix[i][j] = 0;
  52. }
  53. }
  54. //System.out.println(n + " " + root);
  55. for (int i = 0; i < n - 1; i++) {
  56. u = sc.nextInt();
  57. v = sc.nextInt();
  58. w = sc.nextInt();
  59. //System.out.println(u + " " + v + " " + w);
  60. matrix[u][v] = matrix[v][u] = w;
  61. }
  62. int min = 0;
  63. for (int i = 1; i <= n; i++) {
  64. if (matrix[root][i] > 0) {
  65. min += getMin(i, root);
  66. }
  67. }
  68. System.out.println(min);
  69. }
  70. }
  71.  
  72. public int getMin(int node, int prev) {
  73. int min = 0;
  74. for (int i = 1; i <= n; i++) {
  75. if (matrix[node][i] > 0 && i != prev) {
  76. min += getMin(i, node);
  77. }
  78. }
  79. if(min == 0){
  80. return matrix[node][prev];
  81. } else {
  82. return Math.min(matrix[node][prev], min);
  83. }
  84. }
  85. }
  86.