AlenAntonelli

mi Kruskalito

Jun 12th, 2018
102
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.82 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. #include <queue>
  4. using namespace std;
  5.  
  6. struct grafo
  7. {
  8.     vector< vector< pair<int,int> > > ady;
  9.     priority_queue< pair<int, pair<int,int> > > pq;
  10.     vector<int> isla;
  11.     vector< vector<int> > comp;
  12.    
  13.     int n, m;
  14.    
  15.     void leer()
  16.     {
  17.         cin>>n>>m;
  18.         ady.resize(n+1);
  19.         isla.resize(n+1);
  20.         comp.resize(n+1);
  21.        
  22.         int a, b, k;
  23.         for(int i=0; i<m; i++)
  24.         {
  25.             cin>>a>>b>>k;
  26.             ady[a].push_back( {k, b} );
  27.             ady[b].push_back( {k, a} );
  28.             pq.push( {-k,{a, b}} );
  29.         }
  30.     }
  31.    
  32.     int Kruskal ()
  33.     {
  34.         int PT=0;
  35.        
  36.         for(int i=1; i<=n; i++)
  37.         {
  38.             isla[i] = i;
  39.             comp[i].push_back(i);
  40.         }
  41.        
  42.         while( pq.size() )
  43.         {
  44.             pair<int, pair<int,int> > arista = pq.top();
  45.             pq.pop();
  46.            
  47.             int desde = arista.second.first;
  48.             int hasta = arista.second.second;
  49.            
  50.             cout<<-arista.first<<"("<<desde<<"-"<<hasta<<")"<<endl;
  51.            
  52.             int is1 = isla[desde];
  53.             int is2 = isla[hasta];
  54.            
  55.             if (is1 != is2)
  56.             {
  57.                 PT+=-arista.first;
  58.                
  59.                 if(comp[is1].size()<comp[is2].size())
  60.                     swap(is1, is2);
  61.                    
  62.                 for(int i=0; i<comp[is2].size(); i++)
  63.                 {
  64.                     int x = comp[is2][i];
  65.                     isla[x]=is1;
  66.                     comp[is1].push_back(x);
  67.                 }
  68.                 comp[is2].clear();
  69.             }
  70.         }
  71.        
  72.         return PT;
  73.     }
  74. };
  75.  
  76. int main()
  77. {
  78.     grafo g;
  79.     g.leer();
  80.     cout<<endl<<g.Kruskal();
  81.  
  82.     return 0;
  83. }
Advertisement
Add Comment
Please, Sign In to add comment