Skip to content

Instantly share code, notes, and snippets.

@WSAyan
Last active March 7, 2017 04:49
Show Gist options
  • Save WSAyan/8030a730e9ac72bf8ede4c460620b1e7 to your computer and use it in GitHub Desktop.
Save WSAyan/8030a730e9ac72bf8ede4c460620b1e7 to your computer and use it in GitHub Desktop.
Disjoint set example
#include<iostream>
using namespace std;
int par[100]={0};
int count=0;
void makeset(int n)
{
par[n]=n;
}
int find(int r)
{
if(par[r]==r)
{
return r;
}
else
return par[r]=find(par[r]);
}
void set_union(int a,int b)
{
int u=find(a);
int v=find(b);
if(u==v)
{
cout<<"They are allready connected"<<endl;
}
else
{
par[u]=v;
}
}
int main()
{
int m,n,x,y,u,v;
cin>>m;
for(int i=0;i<m;i++)
{
makeset(i);
}
cin>>n;
for(int i=0;i<n;i++)
{
cin>>x>>y;
set_union(x,y);
}
for(int i=0;i<m;i++)
{
cout<<"["<<i<<"] = "<<par[i]<<endl;
if(i==find(i))
count++;
}
cout<<count<<endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment