AlexandruT

[pbInfo] kruskal

Dec 4th, 2016
113
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.23 KB | None | 0 0
  1. #include <fstream>
  2. #include <algorithm>
  3.  
  4. using namespace std;
  5.  
  6. ofstream fout("kruskal.out");
  7.  
  8. int arbore[1001], x, y, cost, n, m, unific[101], ct;
  9.  
  10. struct muchie
  11. {
  12.     int x, y, cost;
  13. }
  14. a[1001];
  15.  
  16. bool cmp(muchie a, muchie b)
  17. {
  18.     return a.cost < b.cost;
  19. }
  20.  
  21. void CitireMuchii()
  22. {
  23.     ifstream fin("kruskal.in");
  24.     fin >> n >> m;
  25.     for(int i = 1; i <= m; i++)
  26.     {
  27.         fin >> x >> y >> cost;
  28.         a[i].x = x; a[i].y = y;
  29.         a[i].cost = cost;
  30.     }
  31.     fin.close();
  32. }
  33.  
  34. void CreareArbore()
  35. {
  36.     int i = 1, k = 0, aux;
  37.     for(int j = 1; j <= n; j++) unific[j]=j;
  38.     while(k < n - 1)
  39.     {
  40.         if(unific[a[i].x] != unific[a[i].y])
  41.         {
  42.             ct = ct + a[i].cost;
  43.             k++;
  44.             arbore[k] = i;
  45.             aux = unific[a[i].y];
  46.             for(int j = 1; j <= n; j++)
  47.                 if(unific[j] == aux) unific[j] = unific[a[i].x];
  48.         }
  49.         i++;
  50.     }
  51. }
  52.  
  53. void AfisareMuchii()
  54. {
  55.     for(int i = 1; i <= n-1; i++)
  56.         fout << a[arbore[i]].x << ' ' << a[arbore[i]].y << '\n';
  57. }
  58.  
  59. int main()
  60. {
  61.     CitireMuchii();
  62.     sort(a, a + m, cmp);
  63.     CreareArbore();
  64.     fout << ct << '\n';
  65.     AfisareMuchii();
  66.     fout.close();
  67.     return 0;
  68. }
Advertisement
Add Comment
Please, Sign In to add comment