Advertisement
Guest User

Untitled

a guest
Oct 4th, 2015
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.02 KB | None | 0 0
  1. /*
  2. * To change this license header, choose License Headers in Project Properties.
  3. * To change this template file, choose Tools | Templates
  4. * and open the template in the editor.
  5. */
  6. package mst;
  7.  
  8. /**
  9. *
  10. * @author Hp
  11. */
  12. import java.io.File;
  13. import java.io.FileNotFoundException;
  14. import java.util.*;
  15. class kru{
  16. int i,j,k,a,b,u,v,n,ne=1;
  17. int min,mincost=0;
  18. int cost[][]=new int[1000][1000];
  19. int parent[]=new int[1000];
  20.  
  21. kru(int n,int e,Scanner sc){
  22. for(i=1;i<=e;i++)
  23. {
  24.  
  25. int x=sc.nextInt();
  26. int y=sc.nextInt();
  27. int q=sc.nextInt();
  28. cost[y][x]=cost[x][y]=q;
  29.  
  30. }
  31. for(i=1;i<=n;i++)
  32. {
  33. for(int ji=1;ji<=n;ji++)
  34. {
  35. if(cost[i][ji]==0)
  36. cost[i][ji]=999;
  37. }
  38. }
  39.  
  40. while(ne < n)
  41. {
  42. for(i=1,min=999;i<=n;i++)
  43. {
  44. for(j=1;j <= n;j++)
  45. {
  46. if(cost[i][j] < min)
  47. {
  48. min=cost[i][j];
  49. a=u=i;
  50. b=v=j;
  51. }
  52. }
  53. }
  54. u=find(u);
  55. v=find(v);
  56. if(uni(u,v)!=0)
  57. {
  58. System.out.println(a+" "+b);
  59. ne++;
  60. mincost +=min;
  61. }
  62. cost[a][b]=cost[b][a]=999;
  63. }
  64. System.out.println("min_cost"+mincost);
  65. }
  66. int find(int i)
  67. {
  68. while(parent[i]!=0)
  69. i=parent[i];
  70. return i;
  71. }
  72. int uni(int i,int j)
  73. {
  74. if(i!=j)
  75. {
  76. parent[j]=i;
  77. return 1;
  78. }
  79. return 0;
  80. }
  81.  
  82. }
  83. public class Mst {
  84.  
  85. /**
  86. * @param args the command line arguments
  87. */
  88. public static void main(String[] args) throws FileNotFoundException {
  89. // TODO code application logic here
  90. File file=new File("C:\\Users\\Student\\Desktop\\shosho\\mst-2015-10-03\\mst\\src\\mst\\input.txt");
  91. Scanner sc=new Scanner(file);
  92. int n=sc.nextInt();
  93. int e=sc.nextInt();
  94. kru m=new kru(n,e,sc);
  95.  
  96. }
  97.  
  98. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement