Advertisement
rotti321

Kruskal

May 18th, 2021
722
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.14 KB | None | 0 0
  1. #include <iostream>
  2. #include <fstream>
  3. #define INFINIT 1000000000
  4. using namespace std;
  5.  
  6. ifstream fin("kruskal.in");
  7. ofstream fout("kruskal.out");
  8.  
  9. struct muchie{
  10.     int i,j,cost;
  11. };
  12.  
  13. int n , m , t[105];
  14.  
  15. muchie x[5000];
  16. int v[5000];
  17.  
  18. int main()
  19. {
  20.     fin >> n >> m;
  21.    
  22.     for(int i = 0 ; i < m ; ++i)
  23.         fin >> x[i].i >> x[i].j >> x[i].cost;
  24.    
  25.     for(int i = 0 ; i < m - 1; i ++)
  26.         for(int j = i + 1 ; j < m ; ++j)
  27.             if(x[i].cost > x[j].cost)
  28.             {
  29.                 muchie aux = x[i];
  30.                 x[i] = x[j];
  31.                 x[j] = aux;
  32.             }
  33.     for(int i =1 ; i <= n ; ++i)
  34.         t[i] = i;
  35.     int S = 0, cnt = 0;
  36.     for(int i = 0 ; i < m && cnt < n ; i ++)
  37.         if(t[x[i].i] != t[x[i].j])
  38.         {
  39.             v[i] = 1;
  40.             S += x[i].cost;
  41.             int ai = t[x[i].i], aj = t[x[i].j];
  42.             for(int j =1 ; j <= n ; ++j)
  43.                 if(t[j] == aj)
  44.                     t[j] = ai;
  45.         }
  46.     fout << S << "\n";
  47.     for(int i = 0 ; i < m ; ++i)
  48.         if(v[i] == 1)
  49.             fout << x[i].i << " " << x[i].j << "\n";
  50.     return 0;
  51. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement