Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include<iostream>
- using namespace std;
- void make(int n,int parent[],int size[])
- {
- parent[n] = n;
- size[n] = 1;
- }
- int find(int v ,int parent[])
- {
- if(parent[v] == v)
- return v;
- else
- return parent[v] = find(parent[v],parent);
- }
- void Union(int v1,int v2,int parent[],int size[])
- {
- v1 = find(v1,parent);
- v2 = find(v2,parent);
- if(v1 != v2)
- {
- if(size[v1] > size[v2])
- {
- parent[v2] = v1;
- size[v1] += size[v2];
- }
- else
- {
- parent[v1] = v2;
- size[v2] += size[v1];
- }
- }
- }
- struct Edges
- {
- int v1,v2;
- int weight;
- };
- int compare(const void* ptr1, const void *ptr2)
- {
- Edges *p1 = (Edges*)ptr1;
- Edges *p2 = (Edges*)ptr2;
- return ((p1->weight) - (p2->weight));
- }
- int main()
- {
- int m,n;
- cin>>m>>n;
- int parent[n];
- int size[n];
- for(int i = 1; i<=n ; ++i)
- {
- make(i,parent,size);
- }
- Edges *EdgeArr = new Edges[m];
- for(int i = 0 ; i < m ; ++i)
- {
- cin>>EdgeArr[i].v1;
- cin>>EdgeArr[i].v2;
- cin>>EdgeArr[i].weight;
- }
- qsort(EdgeArr,m,sizeof(struct Edges),compare);
- for(int i = 0 ; i < m ; ++i)
- {
- Edges edg = EdgeArr[i];
- int v1 = edg.v1;
- int v2 = edg.v2;
- int wt = edg.weight;
- if(find(v1,parent) == find(v2,parent))
- continue;
- Union(v1,v2,parent,size);
- cout<< v1 << " " << v2 <<endl;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement