Advertisement
NoHatred0

111

May 9th, 2013
45
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.24 KB | None | 0 0
  1. #include <iostream>
  2. #include <fstream>
  3. using namespace std;
  4. ifstream f("kruskal.in");
  5. ofstream g("kruskal.out");
  6.  
  7. int n,m,M[100],p,cost=0;
  8. struct muchie
  9. {
  10. int x,y,c;
  11. }v[100],aux;
  12. void citire()
  13. {
  14. int i;
  15. f>>n>>m;
  16. for(i=1;i<=m;i++)
  17. {
  18. f>>v[i].x;
  19. f>>v[i].y;
  20. f>>v[i].c;
  21. }
  22. }
  23. void quicksort(int s,int d)
  24. {
  25. int i,j,pivot;
  26. if(s<d)
  27. {
  28. i=s;
  29. j=d;
  30. pivot=v[s].c;
  31. while(i<j)
  32. {
  33. while(pivot>=v[i].c) i++;
  34. while(pivot<v[j].c) j--;
  35. if(i<j)
  36. {
  37. aux=v[i];v[i]=v[j];v[j]=aux;
  38. }
  39. }
  40. aux=v[s];
  41. v[s]=v[j];
  42. v[j]=aux;
  43. quicksort(s,j-1);
  44. quicksort(j+1,d);
  45. }
  46. }
  47. int main()
  48. {
  49. int i,j;
  50. citire();
  51. quicksort(1,m);
  52. for(i=1;i<=n;i++)
  53. {
  54. M[i]=i;
  55. }
  56. i=1;
  57. p=0;
  58. while(p<n-1)
  59. {
  60. if(M[v[i].x]!=M[v[i].y])
  61. {
  62. p++;
  63. g<<v[i].x<<" "<<v[i].y<<"\n";
  64. cost=cost+v[i].c;
  65. int a=M[v[i].x];
  66. int b=M[v[i].y];
  67. for(j=1;j<=n;j++)
  68. {
  69. if(M[j]==b) M[j]=a;
  70. }
  71. }
  72. i++;
  73. }
  74. g<<"Costul total: "<<cost;
  75. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement