Skip to content

Commit 27196ce

Browse files
authored
DSU_implementation.cpp
DSU implementation in C++ with comments to make the code easily understandable..
1 parent bfb7969 commit 27196ce

File tree

1 file changed

+108
-0
lines changed

1 file changed

+108
-0
lines changed

Diff for: DSU_implementation.cpp

+108
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,108 @@
1+
// D-S-U -> disjoint set and union.....implementation
2+
3+
#include <bits/stdc++.h>
4+
using namespace std;
5+
6+
typedef long long int ll;
7+
using ii= pair<ll,ll>;
8+
#define F first
9+
#define S second
10+
#define MP make_pair
11+
#define PB push_back
12+
13+
14+
ll parent[1001]; // parent[i] stores parent of node i
15+
ll size[1001]; // stores size of a set
16+
17+
18+
void make_set(ll v) // creates a new set consisting of the element v
19+
{
20+
parent[v]=v;
21+
size[v]=1;
22+
}
23+
24+
ll find_set(ll v) // In find_set(v) we actually find the representative or root of the subtree having node v..
25+
{ // As an optimization we use...COMPRESSION BY PATH ...where after finding a certain v...we set
26+
if(parent[v]==v) // v's parent directly to its representative so as to shorten the path for future find_set calls...
27+
{
28+
return v;
29+
}
30+
else
31+
{
32+
return parent[v]=find_set(parent[v]);
33+
}
34+
}
35+
36+
37+
void union_set(ll u,ll v) // UNION OR MERGING 2 CONNECTED COMPONENTS TOGETHER...
38+
{
39+
u= find_set(u);
40+
v= find_set(v);
41+
42+
if(u!=v)
43+
{
44+
if(size[u]<size[v]) // UNION BY SIZE OPTIMIZATION-> attach the tree with lower size to the tree with bigger size...
45+
{ // So that the size of tree may not grow much
46+
swap(u,v);
47+
}
48+
parent[v]=u;
49+
size[u]+=size[v];
50+
}
51+
}
52+
53+
54+
55+
56+
int main()
57+
{
58+
ios_base::sync_with_stdio(false);
59+
cin.tie(NULL);cout.tie(NULL);
60+
61+
62+
// taking inputs..
63+
64+
ll n;
65+
cin>>n;
66+
ll m=n-1;
67+
vector<ii> build;
68+
vector<ii> demo;
69+
70+
for(ll i=1;i<=n;i++)
71+
{
72+
make_set(i);
73+
}
74+
75+
while(m--)
76+
{
77+
ll a,b;
78+
cin>>a>>b;
79+
80+
if(find_set(a)==find_set(b))
81+
{
82+
demo.PB({a,b});
83+
}
84+
else
85+
{
86+
union_set(a,b); // merging the sets containing elements a and b
87+
}
88+
}
89+
90+
for(ll i=2;i<=n;i++)
91+
{
92+
if(find_set(i)!=find_set(1))
93+
{
94+
build.PB({i,1});
95+
union_set(i,1);
96+
}
97+
}
98+
99+
ll x=build.size();
100+
cout<<build.size()<<"\n";
101+
102+
for(ll i=0;i<x;i++)
103+
{
104+
cout<<demo[i].F<<" "<<demo[i].S<<" "<<build[i].F<<" "<<build[i].S<<"\n";
105+
}
106+
107+
108+
}

0 commit comments

Comments
 (0)