Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 84ace16

Browse files
Create quick-union.cpp
1 parent 53c04c5 commit 84ace16

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
#include<bits/stdc++.h>
2+
using namespace std;
3+
#define ll long long int
4+
#define loop(i,N) for(int i=0;i<N;i++)
5+
#define loop_(i,N) for(int i=1;i<=N;i++)
6+
7+
int root(int ar[],int i){
8+
while(i!=ar[i]) i=ar[i];
9+
return i;
10+
}
11+
12+
int find(int ar[],int a){
13+
return root(ar,a);
14+
}
15+
16+
void union_of(int ar[],int a,int b){
17+
int key=root(ar,b);
18+
ar[root(ar,a)]=key;
19+
}
20+
21+
int main(){
22+
int n,a,b;
23+
cin>>n; // no. of elements/sets at start
24+
int q;
25+
cout<<"Enter no. of union operations: ";
26+
cin>>q;
27+
int A[n+1];
28+
loop_(i,n) A[i]=i;
29+
cout<<"Enter pair for union:\n";
30+
while(q--){
31+
cin>>a>>b;
32+
union_of(A,a,b);
33+
}
34+
loop_(i,n) cout<<A[i]<<" ";
35+
cout<<endl;
36+
cout<<"Enter no. of find queries: ";
37+
cin>>q;
38+
cout<<"Enter find pairs:\n";
39+
while(q--){
40+
cin>>a>>b;
41+
if(find(A,a)==find(A,b)) cout<<"In same Set\n";
42+
else
43+
cout<<"In different Sets\n";
44+
}
45+
return 0;
46+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /