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

Down to Zero II

You are given Q queries. Each query consists of a single number N. You can perform any of the 2 operations N on in each move: 1: If we take 2 integers a and b where , N = a * b , then we can change N = max( a, b ) 2: Decrease the value of N by 1. Determine the minimum number of moves required to reduce the value of N to 0. Input Format The first line contains the integer Q.

View Solution →

Truck Tour

Suppose there is a circle. There are N petrol pumps on that circle. Petrol pumps are numbered 0 to (N-1) (both inclusive). You have two pieces of information corresponding to each of the petrol pump: (1) the amount of petrol that particular petrol pump will give, and (2) the distance from that petrol pump to the next petrol pump. Initially, you have a tank of infinite capacity carrying no petr

View Solution →

Queries with Fixed Length

Consider an -integer sequence, . We perform a query on by using an integer, , to calculate the result of the following expression: In other words, if we let , then you need to calculate . Given and queries, return a list of answers to each query. Example The first query uses all of the subarrays of length : . The maxima of the subarrays are . The minimum of these is . The secon

View Solution →


This question is designed to help you get a better understanding of basic heap operations. You will be given queries of types: " 1 v " - Add an element to the heap. " 2 v " - Delete the element from the heap. "3" - Print the minimum of all the elements in the heap. NOTE: It is guaranteed that the element to be deleted will be there in the heap. Also, at any instant, only distinct element

View Solution →

Jesse and Cookies

Jesse loves cookies. He wants the sweetness of all his cookies to be greater than value K. To do this, Jesse repeatedly mixes two cookies with the least sweetness. He creates a special combined cookie with: sweetness Least sweet cookie 2nd least sweet cookie). He repeats this procedure until all the cookies in his collection have a sweetness > = K. You are given Jesse's cookies. Print t

View Solution →

Find the Running Median

The median of a set of integers is the midpoint value of the data set for which an equal number of integers are less than and greater than the value. To find the median, you must first sort your set of integers in non-decreasing order, then: If your set contains an odd number of elements, the median is the middle element of the sorted sample. In the sorted set { 1, 2, 3 } , 2 is the median.

View Solution →