Advertisement
Akatsuki13

Kruskal

Oct 28th, 2016
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.50 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2.  
  3. using namespace std;
  4.  
  5. struct Edge
  6. {
  7.     int source, dest, cost;
  8. };
  9.  
  10. Edge edge[100];
  11. int par[100];
  12. int g[100][100];
  13.  
  14. bool compare(const Edge &x, const Edge &y)
  15. {
  16.     return x.cost<y.cost;
  17. }
  18.  
  19. int find (int v)
  20. {
  21.     if (par[v]==-1) return v;
  22.     par[v] = find(par[v]);
  23.     return par[v];
  24. }
  25.  
  26. void merge (int v1, int v2)
  27. {
  28.     par[v1] = v2;
  29.     return;
  30. }
  31.  
  32. void Kruskal (int v, int e)
  33. {
  34.     int cnt=0, pos=1, source, dest, cost;
  35.     Edge now;
  36.     while(cnt<v-1)
  37.     {
  38.         if (pos>e) return;
  39.         now = edge[pos++];
  40.         source = now.source;
  41.         dest = now.dest;
  42.         cost=now.cost;
  43.         int v1 = find(source);
  44.         int v2 = find(dest);
  45.         if(v1!=v2)
  46.         {
  47.             g[source][dest] = cost;
  48.             merge(v1, v2);
  49.             cnt++;
  50.         }
  51.     }
  52.     return;
  53. }
  54.  
  55. int main()
  56. {
  57.     int v,e;
  58.     scanf("%d%d", &v, &e);
  59.     int i, j;
  60.     int source, dest, cost;
  61.     for(i=0; i<=v; i++)
  62.     {
  63.         par[i]=-1;
  64.     }
  65.     for(i=0; i<e; i++)
  66.     {
  67.         scanf("%d%d%d", &source, &dest, &cost);
  68.         edge[i].source = source;
  69.         edge[i].dest = dest;
  70.         edge[i].cost = cost;
  71.     }
  72.     memset(g, -1, sizeof(g));
  73.     sort (edge, edge+e, compare);
  74.     Kruskal(v, e);
  75.     for(i=0; i<=v; i++)
  76.     {
  77.         for(j=0; j<=v; j++)
  78.         {
  79.             if(g[i][j]!=-1)
  80.             {
  81.                 printf("Vertex %d and %d, cost %d\n", i, j, g[i][j]);
  82.             }
  83.         }
  84.     }
  85.     return 0;
  86. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement