// C# program for the above approach
using System;
public class GFG
{
// Function to perform the find operation
// of disjoint set union
static int Find(int [] parent, int a)
{
return parent[a]
= (parent[a] == a)
? a
: (Find(parent, parent[a]));
}
// Function to find the Union operation
// of disjoint set union
static void Union(int [] parent,
int [] rank,
int [] total,
int a, int b)
{
// Find the parent of a and b
a = Find(parent, a);
b = Find(parent, b);
if (a == b)
return;
// If the rank are the same
if (rank[a] == rank[b]) {
rank[a]++;
}
if (rank[a] < rank[b]) {
int temp = a;
a = b;
b = temp;
}
// Update the parent for node b
parent[b] = a;
// Update the total number of
// elements of a
total[a] += total[b];
}
// Function to find the total element
// of the set which belongs to the
// element queries[i]
static void findTotNumOfSet(int[,] arr,
int [] queries,
int R, int N, int M)
{
// Stores the parent elements
// of the sets
int [] parent = new int[R + 1];
// Stores the rank of the sets
int [] rank = new int[R + 1];
// Stores the total number of
// elements of the sets
int [] total = new int[R + 1];
for (int i = 0; i < total.Length; i++) {
total[i] = 1;
}
for (int i = 1; i < R + 1; i++) {
// Update parent[i] to i
parent[i] = i;
}
for (int i = 0; i < N; i++) {
// Add the arr[i,0] and
// arr[i,1] elements to
// the same set
Union(parent, rank, total,
arr[i,0],
arr[i,1]);
}
for (int i = 0; i < M; i++) {
// Find the parent element of
// the element queries[i]
int P = Find(parent, queries[i]);
// Print the total elements of
// the set which belongs to P
Console.Write(total[P]+ " ");
}
}
// Driver Code
public static void Main(String[] args)
{
int R = 5;
int[,] arr = { { 1, 2 },
{ 2, 3 },
{ 4, 5 } };
int [] queries = { 2, 4, 1, 3 };
int N = arr.GetLength(0);
int M = queries.GetLength(0);
findTotNumOfSet(arr, queries, R, N, M);
}
}
// This code is contributed by shikhasingrajput