GastonFontenla

Kruskal

Aug 11th, 2019
231
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.94 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. #include <algorithm>
  4.  
  5. using namespace std;
  6.  
  7. vector <int> id;
  8. vector <vector <int> > comp;
  9.  
  10. bool unionFind(int a, int b)
  11. {
  12.     int idA = id[a];
  13.     int idB = id[b];
  14.  
  15.     if(idA == idB)
  16.         return false;
  17.  
  18.     int tamA = comp[idA].size();
  19.     int tamB = comp[idB].size();
  20.  
  21.     if(tamA > tamB)
  22.         return unionFind(b, a);
  23.  
  24.     for(const auto nodo:comp[idA])
  25.     {
  26.         comp[idB].push_back(nodo);
  27.         id[nodo] = idB;
  28.     }
  29.  
  30.     comp[idA].clear();
  31.  
  32.     return true;
  33. }
  34.  
  35. void prepararUnionFind(int cantNodos)
  36. {
  37.     ///Llamar a esta función antes de llamar
  38.     ///a unionFind() !!!! IMPORTANTE!!!
  39.  
  40.     ///Cada nodo pertenece a su propio grupo
  41.     comp.resize(cantNodos+1);
  42.     id.resize(cantNodos+1);
  43.  
  44.     for(int i=0; i<cantNodos; i++)
  45.     {
  46.         comp[i].push_back(i);
  47.         id[i] = i;
  48.     }
  49. }
  50.  
  51. struct arista
  52. {
  53.     int desde, hasta, costo;
  54. };
  55.  
  56. bool operator<(const arista &a, const arista &b)
  57. {
  58.     return a.costo < b.costo;
  59. }
  60.  
  61. int main()
  62. {
  63.     int n, m;
  64.     int a, b, c;
  65.     while(cin >> n >> m)
  66.     {
  67.         if(n == 0 && m == 0)
  68.             break;
  69.         vector <arista> aristas(m);
  70.         prepararUnionFind(n);
  71.  
  72.         long long sumaTotal = 0;
  73.  
  74.         for(int i=0; i<m; i++)
  75.         {
  76.             cin >> a >> b >> c;
  77.             aristas[i] = {a, b, c};
  78.             sumaTotal += c;
  79.         }
  80.  
  81.         sort(aristas.begin(), aristas.end());
  82.         long long ahorro = 0;
  83.         for(int i=0; i<m; i++)
  84.         {
  85.             if(unionFind(aristas[i].desde, aristas[i].hasta))
  86.             {
  87.                 ahorro += aristas[i].costo;
  88.             }
  89.         }
  90.         cout << sumaTotal - ahorro << endl;
  91.     }
  92.    
  93.     /**
  94.     Problemas de Arbol de Expansión Mínima:
  95.     https://www.spoj.com/problems/ULM09/
  96.     https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=975
  97.     **/
  98.  
  99.     return 0;
  100. }
Advertisement
Add Comment
Please, Sign In to add comment