Advertisement
Guest User

Untitled

a guest
Sep 21st, 2019
160
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.97 KB | None | 0 0
  1. package CCC;
  2.  
  3. import java.io.*;
  4. import java.util.*;
  5.  
  6. public class ccc02s2p5 {
  7. static int V,E;
  8. Edge[] edge;
  9. int[] parent;
  10. Edge[] mst;
  11. public class Edge implements Comparable<Edge> {
  12. int bvx, bvy, evx, evy, cost;
  13. @Override
  14. public int compareTo(Edge o) {
  15. return this.cost-o.cost;
  16. }
  17. }
  18. public ccc02s2p5(int v, int e) {
  19. V = v;
  20. E = e;
  21. parent = new int[V];
  22. for (int i = 0; i < V; i++) parent[i] = -1;
  23. edge = new Edge[E];
  24. for (int i = 0; i < E; i++) edge[i] = new Edge();
  25. mst = new Edge[V-1];
  26. for (int i = 0; i < V-1; i++) mst[i] = new Edge();
  27. }
  28. public int find(int v) {
  29. if (parent[v] == -1) return v;
  30. else return find(parent[v]);
  31. }
  32. public void union(int pb, int pe) {
  33. parent[pb] = pe;
  34. }
  35.  
  36. public static void main(String[] args) throws IOException {
  37. BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
  38. StringTokenizer st = new StringTokenizer(br.readLine());
  39. int V = Integer.parseInt(st.nextToken());
  40. int E = 0;
  41. for (int i=1; i<V; i++) {
  42. E += i;
  43. }
  44. ccc02s2p5 graph = new ccc02s2p5(V,E);
  45. int[] positions_x = new int[V];
  46. int[] positions_y = new int[V];
  47. for (int i=0; i<V; i++) {
  48. st = new StringTokenizer(br.readLine());
  49. positions_x[i] = Integer.parseInt(st.nextToken());
  50. positions_y[i] = Integer.parseInt(st.nextToken());
  51. }
  52. double[][] distances = new double[V][V];
  53. for (int i=0; i<V; i++) {
  54. for (int j=0; j<V; j++) {
  55. distances[i][j] = Math.sqrt(Math.pow((positions_x[i]-positions_x[j]),2)+Math.pow((positions_y[i]-positions_y[j]),2));
  56. }
  57. }
  58. for (int i = 0; i<V-1; i++) {
  59. for (int j=i+1; j<V; j++) {
  60. graph.edge[i].bvx = positions_x[i];
  61. graph.edge[i].bvy = positions_y[i];
  62. graph.edge[i].evx = positions_x[j];
  63. graph.edge[i].evy = positions_y[j];
  64. graph.edge[i].cost = (int) ((distances[graph.edge[i].bv][graph.edge[i].ev]) * 1000);
  65. }
  66. }
  67. Arrays.sort(graph.edge);
  68. int j = 0;
  69. for (int i = 0; i < E; i++) {
  70. int bv = graph.edge[i].bv, ev = graph.edge[i].ev;
  71. int pb = graph.find(bv), pe = graph.find(ev);
  72. if (pb != pe) {
  73. graph.mst[j].bv = bv;
  74. graph.mst[j].ev = ev;
  75. graph.mst[j].cost = graph.edge[i].cost;
  76. graph.union(pb, pe);
  77. j++;
  78. }
  79. }
  80. int total = 0;
  81. for (int i = 0; i < V-1; i++) {
  82. System.out.println(graph.mst[i].bv + " " + graph.mst[i].ev + " " + graph.mst[i].cost);
  83. total += graph.mst[i].cost;
  84. }
  85. System.out.println(total);
  86. }
  87.  
  88. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement