#Rank Base
#include<bits/stdc++.h>
#define N 10001
using namespace std;
int parent[N+1];
int finds(int x)
{
if(parent[x] < 0)
return x;
return parent[x] = finds(parent[x]);
}
void unions(int a, int b)
{
int u = finds(a);
int v = finds(b);
if(u == v)
cout << "They are already Friends." << "\n";
else
{
if((parent[u] == parent[v]) || (parent[u] < parent[v]))
{
parent[u] += parent[v];
parent[v] = u;
}
else
{
parent[v] += parent[u];
parent[u] = v;
}
cout << a << " and " << b << " They are now Friends." << "\n";
}
}
int main()
{
int n, i, t, x, y;
cout << "Enter Node Number :: ";
cin >> n;
for(i=1; i<=n; i++)
parent[i] = -1;
cout << "\nEnter Union Operation Number :: ";
cin >> t;
cout << "\nEnter Two Node For Union Operation " << t << " Times :: " << "\n";
for(i=1; i<=t; i++)
{
cin >> x >> y;
unions(x, y);
}
cout << "\n";
for(i=1; i<=n; i++)
{
if(parent[i] < 0)
cout << "Node " << i << " Parent itself." << "\n";
else
cout << "Node " << i << " parent is " << parent[i] << "\n";
}
return 0;
}
Comments
Post a Comment