GastonFontenla

Pre-solución Grafo enorme XOR

Jul 11th, 2019
190
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.77 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2.  
  3. using namespace std;
  4.  
  5. struct arista
  6. {
  7.     int desde, hasta, costo;
  8. };
  9.  
  10. bool operator<(const arista &a, const arista &b)
  11. {
  12.     return a.costo > b.costo;
  13. }
  14.  
  15. vector <vector <arista> > ady;
  16. vector <int> id;
  17. vector <vector <int> > comp;
  18.  
  19. bool unionfind(int a, int b)
  20. {
  21.     int idA = id[a];
  22.     int idB = id[b];
  23.  
  24.     if(idA == idB)
  25.         return false;
  26.  
  27.     int tA = comp[idA].size();
  28.     int tB = comp[idB].size();
  29.  
  30.     if(tB > tA)
  31.     {
  32.         swap(a, b);
  33.         swap(idA, idB);
  34.         swap(tA, tB);
  35.     }
  36.  
  37.     for(int i=0; i<tB; i++)
  38.     {
  39.         comp[idA].push_back(comp[idB][i]);
  40.         id[comp[idB][i]] = idA;
  41.     }
  42.  
  43.     return true;
  44. }
  45.  
  46. int main()
  47. {
  48.     int n;
  49.     cin >> n;
  50.  
  51.     ady.resize(n);
  52.     comp.resize(n);
  53.     id.resize(n);
  54.  
  55.     for(int i=0; i<n; i++)
  56.     {
  57.         comp[i].push_back(i);
  58.         id[i] = i;
  59.     }
  60.  
  61.     priority_queue <arista> pq;
  62.  
  63.     for(int i=0; i<n; i++)
  64.     {
  65.         for(int j=0; j<n; j++)
  66.         {
  67.             if(i != j)
  68.             {
  69.                 ady[i].push_back({i, j, i^j});
  70.                 pq.push({i, j, i^j});
  71.             }
  72.         }
  73.     }
  74.  
  75.     vector <arista> MST;
  76.  
  77.     while(pq.size())
  78.     {
  79.         arista ar = pq.top();
  80.         pq.pop();
  81.  
  82.         if(unionfind(ar.desde, ar.hasta))
  83.             MST.push_back(ar);
  84.     }
  85.  
  86.     int sumaTotal = 0;
  87.     map<int, int> mapa;
  88.     for(int i=0; i<MST.size(); i++)
  89.     {
  90.         //cout << MST[i].desde << " a " << MST[i].hasta << " con " << MST[i].costo << endl;
  91.         sumaTotal += MST[i].costo;
  92.         mapa[MST[i].costo]++;
  93.     }
  94.  
  95.     cout << "Costo total MST: " << sumaTotal << endl;
  96.  
  97.     for(auto i:mapa)
  98.     {
  99.         cout << i.first << ": " << i.second << endl;
  100.     }
  101.  
  102.     return 0;
  103. }
Advertisement
Add Comment
Please, Sign In to add comment