This repository was archived by the owner on May 5, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUnion-disjoint.cpp
More file actions
69 lines (60 loc) · 1.29 KB
/
Union-disjoint.cpp
File metadata and controls
69 lines (60 loc) · 1.29 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
// This is the implementation of union disjoint data structure
#include <bits/stdc++.h>
#include <vector>
#include <queue>
using namespace std;
struct node{
int data;
int parent;
int size;
};
void unionds(struct node graph[], int u, int v);
void findelem(int u,struct node graph[]);
int main(){
int n;
cout<<"Enter the number of vertices\n";
cin>>n;
struct node graph[n];
int temp;
for (int i=0; i<n;i++){
graph[i].size = 1;
graph[i].data = i;
graph[i].parent = i;
}
cout<<"Enter the number of unions, you'd wish to perform\n";
int size;
cin>>size;
cout<<"Enter the nodes to perform Union on \n";
for (int i=0; i<size; i++){
int m, n;
cin>>m>>n;
unionds(graph, m, n);
}
cout<<" Enter the element to find\n";
int u;
cin>>u;
findelem(u, graph);
return 0;
}
void unionds(struct node graph[], int u, int v){
int temp1 = graph[u].size;
if(graph[u].size == graph[v].size){
graph[u].parent = v;
graph[v].size+=temp1;
}
else if (graph[u].size > graph[v].size){
graph[u].size+=graph[v].size;
graph[v].parent = u;
}
else{
graph[v].size+=temp1;
graph[u].parent = v;
}
}
void findelem(int u, struct node graph[]){
struct node nd = graph[u];
while(nd.parent!= nd.data){
nd = graph[nd.parent];
}
cout<<u<<" belongs to the set containing "<<nd.parent<<"\n";
}