Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <vector>
- #include <queue>
- using namespace std;
- struct grafo
- {
- vector< vector< pair<int,int> > > ady;
- priority_queue< pair<int, pair<int,int> > > pq;
- vector<int> isla;
- vector< vector<int> > comp;
- int n, m;
- void leer()
- {
- cin>>n>>m;
- ady.resize(n+1);
- isla.resize(n+1);
- comp.resize(n+1);
- int a, b, k;
- for(int i=0; i<m; i++)
- {
- cin>>a>>b>>k;
- ady[a].push_back( {k, b} );
- ady[b].push_back( {k, a} );
- pq.push( {-k,{a, b}} );
- }
- }
- int Kruskal ()
- {
- int PT=0;
- for(int i=1; i<=n; i++)
- {
- isla[i] = i;
- comp[i].push_back(i);
- }
- while( pq.size() )
- {
- pair<int, pair<int,int> > arista = pq.top();
- pq.pop();
- int desde = arista.second.first;
- int hasta = arista.second.second;
- cout<<-arista.first<<"("<<desde<<"-"<<hasta<<")"<<endl;
- int is1 = isla[desde];
- int is2 = isla[hasta];
- if (is1 != is2)
- {
- PT+=-arista.first;
- if(comp[is1].size()<comp[is2].size())
- swap(is1, is2);
- for(int i=0; i<comp[is2].size(); i++)
- {
- int x = comp[is2][i];
- isla[x]=is1;
- comp[is1].push_back(x);
- }
- comp[is2].clear();
- }
- }
- return PT;
- }
- };
- int main()
- {
- grafo g;
- g.leer();
- cout<<endl<<g.Kruskal();
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment