Advertisement
Mattia-Iojica

Kruskal

Apr 18th, 2019
167
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.79 KB | None | 0 0
  1. #include <iostream>
  2. #include <fstream>
  3. #define nmaxvf 50
  4. #define nmaxmuchii nmaxvf*(nmaxvf-1)/2
  5. using namespace std;
  6.  
  7. struct Muchie{ int e1,e2,cost; };
  8. Muchie G[nmaxmuchii];
  9.  
  10. int A[nmaxvf], c[nmaxvf];
  11. int n,m;
  12.  
  13. void initializare()
  14. {
  15.     int i;
  16.     ifstream fin("kruskal.in");
  17.     fin>>n>>m;
  18.     for(int i=1;i<=m;i++)
  19.         fin>>G[i].e1>>G[i].e2>>G[i].cost;
  20.     for(i=1;i<=n;i++)
  21.         c[i]=i;
  22.         fin.close();
  23. }
  24.  
  25. void afisare()
  26. {
  27.     int costapm=0;
  28.     cout<<"arborele partial de cost minim este:"<<endl;
  29.     for(int i=1;i<n;i++)
  30.        {
  31.             cout<<"["<<G[A[i]].e1<<","<<G[A[i]].e2<<"] cost="<<G[A[i]].cost<<endl;
  32.     costapm+=G[A[i]].cost;
  33.     cout<<"costul apm= "<<costapm<<endl;
  34.        }
  35. }
  36.  
  37. void sortm(int st, int dr)
  38. {
  39.     int i,j;
  40.     Muchie x;
  41.     if(st<dr)
  42.     {
  43.         x=G[st]; i=st; j=dr;
  44.         while(i<j)
  45.         {
  46.             while(i<j && G[j].cost>=x.cost)
  47.                 j--;
  48.             G[i]=G[j];
  49.             while(i<j && G[i].cost<=x.cost)
  50.                 i++;
  51.             G[j]=G[i];
  52.         }
  53.         G[i]=x;
  54.         sortm(st,i-1);
  55.         sortm(i+1,dr);
  56.     }
  57. }
  58.  
  59. int main()
  60. {
  61.     int i,j,min,max,nrmsel;
  62.     initializare();
  63.     sortm(1,m);
  64.     nrmsel=0; //nr muchii selectate
  65.     for(i=1;nrmsel<n-1;i++)
  66.         if(c[G[i].e1]!=c[G[i].e2])
  67.         //muchia i nu formeaza cicluri cu cele deja selectate
  68.     {
  69.         //selectez muchia i
  70.         A[++nrmsel]=i;
  71.         //unific componentele conexe ale extremitatilor
  72.         if(c[G[i].e1]<c[G[i].e2])
  73.         {
  74.             min=c[G[i].e1];
  75.             max=c[G[i].e2];
  76.         }
  77.         else
  78.         {
  79.             min=c[G[i].e2];
  80.             max=c[G[i].e1];
  81.         }
  82.         for(j=1;j<=n;j++)
  83.         if(c[j]==max)
  84.             c[j]=min;
  85.     }
  86.     afisare();
  87. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement