Merging Communities

Problem Statement :

People connect with each other in a social network. A connection between Person I and Person J is represented as . When two persons belonging to different communities connect, the net effect is the merger of both communities which I and J belongs to.

At the beginning, there are N people representing N communities. Suppose person 1 and 2 connected and later 2 and 3 connected, then ,1 , 2 and 3 will belong to the same community.

There are two type of queries:

1. M I J =>  communities containing person  and  merged (if they belong to different communities).

2. Q I =>  print the size of the community to which person  belongs.

Input Format

The first line of input will contain integers N and Q, i.e. the number of people and the number of queries.
The next Q lines will contain the queries.

Constraints :

1  <=  N  <= 10^5
1  <=  Q   <= 2 * 10^5

Output Format

The output of the queries.

Solution :

                            Solution in C :

In C ++ :

#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;

int f[100005], s[100005];
int find(int x) {
    if (x == f[x]) return x;
    return f[x] = find(f[x]);
void merge(int x, int y) {
    int fx = find(x), fy = find(y);
    if (fx == fy) return;
    if (s[fx] > s[fy]) {
        f[fy] = fx;
        s[fx] += s[fy];
    } else {
        f[fx] = fy;
        s[fy] += s[fx];
int Q, N;
char c[5];
int main() {
    scanf("%d%d", &N, &Q);
    for (int i = 1; i <= N; ++i) f[i] = i, s[i] = 1;
    for (int i = 0; i < Q; ++i) {
        scanf("%s", c);
        if (c[0] == 'M') {
            int x, y; scanf("%d%d", &x, &y);
            merge(x, y);
        } else {
            int x; scanf("%d", &x);
            printf("%d\n", s[find(x)]);
    return 0;

In Java :

import java.util.Arrays;
import java.util.Scanner;

public class MergingCommunities {
	public static void main(String[] args) throws Exception {
		Scanner sc = new Scanner(;
		int n = sc.nextInt();
		int q = sc.nextInt();

		parent = new int[n];
		for (int i = 0; i < n; i++)
			parent[i] = i;

		size = new int[n];
		Arrays.fill(size, 1);

		while (q-- != 0) {
			// System.out.println(Arrays.toString(parent));
			// System.out.println(Arrays.toString(size));
			// System.out.println();
			String type =;
			if (type.equals("Q"))
				System.out.println(size[findSet(sc.nextInt() - 1)]);
				union(sc.nextInt() - 1, sc.nextInt() - 1);


	static int[] parent;
	static int[] size;

	static int findSet(int x) {
		return parent[x] == x ? x : (parent[x] = findSet(parent[x]));

	static void union(int x, int y) {
		if (findSet(x) != findSet(y))
			size[findSet(x)] = size[findSet(y)] = size[findSet(x)]
					+ size[findSet(y)];
		parent[findSet(x)] = findSet(y);

In  C :

#define mem(a,v) memset(a,v,sizeof(a))
long int parent[100005],rank[100005],val[100005];
long int find(long int x)
	return x;
	return find(parent[x]);
void _union(long int x,long int y)
	long int vv,dd=find(x);
	long int hh=find(y);
	else if(rank[hh]<rank[dd])
int main()
	long int c,d,t,i,e;
	char ff[3];

	return 0;

In Python3 :

[N,Q]=[int(x) for x in input().split()]
ds = [[i,1] for i in range(0,N+1)]
for q in range(Q):
    inp = input().split()
    if inp[0] == 'M':
        ind1 = int(inp[1])
        ind2 = int(inp[2])
        ind3 = ind2
        while ds[ind1][0] != ind1:
            ind1 = ds[ind1][0]
        while ds[ind2][0] != ind2:
            ind2 = ds[ind2][0]
        if ind1 == ind2:
        while ind3 != ind2:
            ind4 = ds[ind3][0]
            ds[ind3][0] = ind1
            ind3 = ind4
        ds[ind2][0] = ind1
        ds[ind1][1] += ds[ind2][1]
        ind1 = int(inp[1])
        while ds[ind1][0] != ind1:
            ind1 = ds[ind1][0]

View More Similar Problems

Binary Search Tree : Lowest Common Ancestor

You are given pointer to the root of the binary search tree and two values v1 and v2. You need to return the lowest common ancestor (LCA) of v1 and v2 in the binary search tree. In the diagram above, the lowest common ancestor of the nodes 4 and 6 is the node 3. Node 3 is the lowest node which has nodes and as descendants. Function Description Complete the function lca in the editor b

View Solution →

Swap Nodes [Algo]

A binary tree is a tree which is characterized by one of the following properties: It can be empty (null). It contains a root node only. It contains a root node with a left subtree, a right subtree, or both. These subtrees are also binary trees. In-order traversal is performed as Traverse the left subtree. Visit root. Traverse the right subtree. For this in-order traversal, start from

View Solution →

Kitty's Calculations on a Tree

Kitty has a tree, T , consisting of n nodes where each node is uniquely labeled from 1 to n . Her friend Alex gave her q sets, where each set contains k distinct nodes. Kitty needs to calculate the following expression on each set: where: { u ,v } denotes an unordered pair of nodes belonging to the set. dist(u , v) denotes the number of edges on the unique (shortest) path between nodes a

View Solution →

Is This a Binary Search Tree?

For the purposes of this challenge, we define a binary tree to be a binary search tree with the following ordering requirements: The data value of every node in a node's left subtree is less than the data value of that node. The data value of every node in a node's right subtree is greater than the data value of that node. Given the root node of a binary tree, can you determine if it's also a

View Solution →

Square-Ten Tree

The square-ten tree decomposition of an array is defined as follows: The lowest () level of the square-ten tree consists of single array elements in their natural order. The level (starting from ) of the square-ten tree consists of subsequent array subsegments of length in their natural order. Thus, the level contains subsegments of length , the level contains subsegments of length , the

View Solution →

Balanced Forest

Greg has a tree of nodes containing integer data. He wants to insert a node with some non-zero integer value somewhere into the tree. His goal is to be able to cut two edges and have the values of each of the three new trees sum to the same amount. This is called a balanced forest. Being frugal, the data value he inserts should be minimal. Determine the minimal amount that a new node can have to a

View Solution →