Advertisement
Guest User

Krusky

a guest
Jan 29th, 2020
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.23 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. #define nax 102
  3.  
  4. using namespace std;
  5.  
  6. ifstream f("kruskal.in");
  7. ofstream g("kruskal.out");
  8.  
  9. int n, m;
  10. int L[2*nax];
  11. vector<int> ans;
  12.  
  13. struct muchie
  14. {
  15.     int x, y, cost;
  16. }u[2*nax];
  17.  
  18. void init()
  19. {
  20.     int i;
  21.     for(i = 1; i <= n; ++i)
  22.         L[i] = i;
  23. }
  24.  
  25. void Read()
  26. {
  27.     int x, y, cost, i = 0;
  28.     f >> n >> m;
  29.     while(f >> x >> y >> cost)
  30.     {
  31.         ++i;
  32.         u[i].x = x;
  33.         u[i].y = y;
  34.         u[i].cost = cost;
  35.     }
  36.     sort(u+1, u+1+m, [&](muchie m1, muchie m2){return (m1.cost < m2.cost);});
  37. }
  38.  
  39. int main()
  40. {
  41.     int i = 1, j, k = 0, x, y, cost = 0;
  42.     Read();
  43.     init();
  44.  
  45. //    g << "APM este format din muchiile: ";
  46.     while(k < n - 1)
  47.     {
  48.         if(L[u[i].x] != L[u[i].y])
  49.         {
  50.             ++k;
  51.             cost += u[i].cost;
  52.             x = L[u[i].y];
  53.             y = L[u[i].x];
  54.  
  55.             ans.push_back(u[i].x);
  56.             ans.push_back(u[i].y);
  57.  
  58.             for(j = 1; j <= n; ++j)
  59.                 if(L[j] == x)
  60.                     L[j] = y;
  61.         }
  62.         ++i;
  63.     }
  64.     ans.shrink_to_fit();
  65.     g << cost << "\n";
  66.     for(i = 0; i < ans.size()-1; i += 2)
  67.         g << ans[i] << " " << ans[i+1] << "\n";
  68.     return 0;
  69. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement