#include<bits/stdc++.h>
using namespace std;
int parent[1010];
int finds(int x)
{
if(parent[x] == x)
return x;
return parent[x] = finds(parent[x]);
}
void unions(int x, int y)
{
int u = finds(x);
int v = finds(y);
if(u != v)
parent[v] = u;
}
int main()
{
int n, t, x, y;
cout << "Enter Number of Node :: ";
cin >> n;
for(int i=1;i<=n;i++)
parent[i] = i;
cout << "Enter Union Operation Number :: ";
cin >> t;
cout << "Enter Node for Union Operation :: \n";
for(int i=1;i<=t;i++)
{
cin >> x >> y;
unions(x, y);
}
for(int i=1;i<=n;i++)
{
if(parent[i] == i)
cout << "Node " << i << " Parent itself." << "\n";
else
cout << "Node " << i << " parent is " << parent[i] << "\n";
}
return 0;
}
Comments
Post a Comment