Advertisement
mateusz1239196

kruskal

Apr 11th, 2022
965
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.93 KB | None | 0 0
  1. #include <iostream>
  2. #include <string>
  3. #include <math.h>
  4. #include <fstream>
  5. #include <time.h>
  6.  
  7. using namespace std;
  8.  
  9. struct vert{
  10.   int x, y; // reprezentacja punktu na p³aszczyŸnie
  11. };
  12.  
  13. struct edge
  14. {
  15.   int a, b; // numery wierzcho³ków, które krawêdŸ ³¹czy
  16.   float len;  // jej d³ugoœæ
  17.   bool chosen; // czy zosta³a wybrana
  18. };
  19.  
  20.  
  21. void InsertSort(edge t[], int r)
  22. {
  23.     for(int i=1; i< r; i++)
  24.     {   int idx = i-1;
  25.         edge temp = t[i];
  26.         while(idx >= 0 && t[idx].len> temp.len)
  27.          {
  28.            t[idx+1] = t[idx];
  29.            idx--;
  30.          }
  31.         t[idx+1] = temp;
  32.     }
  33. }
  34.  
  35.  
  36. float dist(vert A, vert B)
  37. {
  38.   return sqrt(pow(A.x - B.x,2)+pow(A.y - B.y,2));
  39. }
  40.  
  41. edge* Kruskal(vert V[], int how_many)
  42. {
  43.   int *color = new int[how_many];
  44.   for(int i=0; i< how_many; i++) color[i] = i;
  45.  
  46.   int n = 0;
  47.  
  48.   int num_of_edges = how_many * (how_many-1) *0.5;
  49.   cout<<"num of edges"<<num_of_edges<<endl;
  50.  
  51.   edge *E = new edge[num_of_edges];
  52.   for(int i=0; i< how_many; i++)
  53.     for(int j=i+1; j< how_many; j++)
  54.     {
  55.       E[n].a = i; E[n].b = j;
  56.       E[n].len = dist(V[i],V[j]);
  57.       E[n].chosen = false;
  58.       n++;
  59.     }
  60.  
  61.  
  62.  
  63.  
  64.   InsertSort(E, num_of_edges);
  65.  
  66.   int counter = 0;
  67.   for(int i=0; i< num_of_edges; i++)
  68.   {
  69.     int c1 = color[E[i].a];
  70.     int c2 = color[E[i].b];
  71.     if (c1 != c2)
  72.     {
  73.       E[i].chosen = true;
  74.       for(int j=0; j< how_many; j++)
  75.         if(color[j]==c2) color[j]=c1;
  76.       counter++;
  77.       if (counter==how_many-1)
  78.         break;
  79.     }
  80.  
  81.   }
  82.  
  83.  
  84.  
  85.   return E;
  86. }
  87.  
  88.  
  89.  
  90. int main()
  91. {
  92.   vert* V = new vert[6];
  93.   V[0].x = 1; V[0].y = 1;
  94.   V[1].x = 2; V[1].y = 2;
  95.   V[2].x = 1; V[2].y = 2;
  96.   V[3].x = 1; V[3].y = 0;
  97.  
  98.   V[4].x = 17; V[4].y = 1;
  99.   V[5].x = 20; V[5].y = 1;
  100.  
  101.   edge* res;
  102.   res = Kruskal(V,6);
  103.  
  104.   for(int i=0; i<15; i++)
  105.     cout<<res[i].a<<"--"<<res[i].b<<" dlugosc "<<res[i].len<<" "<<(res[i].chosen?"*":"")<<endl;
  106.  
  107.  
  108. }
  109.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement