Source code for submission s868

spider.java

  1. /*
  2.  * To change this template, choose Tools | Templates
  3.  * and open the template in the editor.
  4.  */
  5.  
  6. /**
  7.  *
  8.  * @author cteam040
  9.  */
  10. import java.util.*;
  11. import java.io.*;
  12. public class spider {
  13. public static void main(String[] s) throws Exception {
  14. String ln;
  15. next_case:
  16. while((ln=br.readLine())!=null)
  17. {
  18.  
  19. st = new StringTokenizer(ln);
  20. int nodes = Integer.parseInt(st.nextToken());
  21. int nEdges = Integer.parseInt(st.nextToken());
  22. PriorityQueue<Edge> edges = new PriorityQueue<Edge>();
  23. Edge longest = new Edge(0,0,-1);
  24. for(int i=0;i<nEdges;i++)
  25. {
  26. ln = br.readLine();
  27. st = new StringTokenizer(ln);
  28. int node1 = Integer.parseInt(st.nextToken())-1;
  29. int node2 = Integer.parseInt(st.nextToken())-1;
  30. int cena = Integer.parseInt(st.nextToken());
  31. Edge ne = null;
  32. if(node1>node2)
  33. ne = new Edge(node2,node1,cena);
  34. else
  35. ne = new Edge(node1,node2,cena);
  36. edges.add(ne);
  37. if(ne.compareTo(longest)>0)
  38. longest = ne;
  39. }
  40. int[] components = new int[nodes];
  41. for(int i=0;i<nodes;i++)
  42. components[i] = i;
  43. components[longest.a] = longest.b;
  44. long cena = -longest.cena;
  45. for(int pridano=0;pridano<nodes-1 && !edges.isEmpty();)
  46. {
  47. Edge cur = edges.poll();
  48. int ca = findRoot(components, cur.a);
  49. int cb = findRoot(components, cur.b);
  50. if(ca==cb)
  51. continue;
  52. pridano++;
  53. cena += cur.cena;
  54. components[ca] = cb;
  55. }
  56. int someroot = findRoot(components, 0);
  57. for(int i=1;i<nodes;i++)
  58. {
  59. if(findRoot(components, i)!=someroot)
  60. {
  61. System.out.println("disconnected");
  62. continue next_case;
  63. }
  64. }
  65. System.out.println(cena);
  66. }
  67. }
  68.  
  69.  
  70. public static int findRoot(int[] comps, final int i)
  71. {
  72. int j=i;
  73. while(comps[j]!=j)
  74. {
  75. j = comps[j];
  76. }
  77. comps[i] = j;
  78. return j;
  79. }
  80.  
  81. public static class Edge implements Comparable<Edge>
  82. {
  83. int a,b,cena;
  84.  
  85. public Edge(int a, int b, int cena) {
  86. this.a = a;
  87. this.b = b;
  88. this.cena = cena;
  89. }
  90.  
  91. public int compareTo(Edge arg0) {
  92. return cena-arg0.cena;
  93. }
  94.  
  95. }
  96. }
  97.