Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

disjoint_sets.cpp: Added Disjoint sets data structure #857

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
80 changes: 80 additions & 0 deletions Data Structures/disjoint_sets.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
#include <bits/stdc++.h>
using namespace std;

class disjoint_set
{
public:
vector<int> ds;
disjoint_set(int n)
{
ds.resize(n + 1);
for(int i = 1; i <= n; i++)
{
make_set(i);
}
}
void make_set(int node);
int find_set(int node);
void union_sets(int node_a, int node_b);
void print_disjoint_sets();
};

void disjoint_set::make_set(int node)
{
ds[node] = node;
}

int disjoint_set::find_set(int node)
{
if(ds[node] == node)
return node;
else
return ds[node] = find_set(ds[node]);
}

void disjoint_set::union_sets(int node_a, int node_b)
{
ds[node_a] = node_b;
}

void disjoint_set::print_disjoint_sets()
{
map<int, vector<int>> disjoint_sets;
for(int i = 1; i <= ds.size(); i++)
{
disjoint_sets[find_set(ds[i])].push_back(i);
}
cout << "Disjoint sets are following:\n";
int set_number = 1;
for(auto it : disjoint_sets)
{
cout << "Set " << set_number++ << ": ";
for(auto jt : it.second)
{
cout << jt << " ";
}
cout << "\n";
}
}

int main()
{
int nodes;
cin >> nodes;
disjoint_set dsu(nodes);
int edges;
cin >> edges;
for(int i = 0; i < edges; i++)
{
int u,v;
cin >> u >> v;
int parent_u = dsu.find_set(u);
int parent_v = dsu.find_set(v);
if(parent_u != parent_v)
{
dsu.union_sets(parent_u, parent_v);
}
}
dsu.print_disjoint_sets();
return 0;
}