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 :



title-img


                            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(System.in);
		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 = sc.next();
			if (type.equals("Q"))
				System.out.println(size[findSet(sc.nextInt() - 1)]);
			else
				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 :




#include<stdio.h>
#define mem(a,v) memset(a,v,sizeof(a))
long int parent[100005],rank[100005],val[100005];
long int find(long int x)
{
	if(parent[x]==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);
	if(dd!=hh)
	{
	if(rank[hh]>rank[dd])
	{
		parent[dd]=hh;
	val[hh]+=val[dd];
	}
	else if(rank[hh]<rank[dd])
	{
		parent[hh]=dd;
	val[dd]+=val[hh];
	}
	else
	{
	parent[hh]=dd;
	val[dd]+=val[hh];
	rank[dd]++;	
	}
	}
}
int main()
{
	long int c,d,t,i,e;
	char ff[3];

for(i=0;i<=100005;i++)
	{
		parent[i]=i;
		val[i]=1;
		rank[i]=1;
	}
	scanf("%ld%ld",&c,&d);
	for(i=0;i<=c;i++)
	parent[i]=i;
	while(d--)
	{
		scanf("%s",ff);
		if(ff[0]=='M')
		{
		scanf("%ld%ld",&e,&t);
		_union(e,t);
		}
		else
		{
			scanf("%ld",&e);
		printf("%ld\n",val[find(e)]);
		}
	}
	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:
            continue
        while ind3 != ind2:
            ind4 = ds[ind3][0]
            ds[ind3][0] = ind1
            ind3 = ind4
        ds[ind2][0] = ind1
        ds[ind1][1] += ds[ind2][1]
    else:
        ind1 = int(inp[1])
        while ds[ind1][0] != ind1:
            ind1 = ds[ind1][0]
        print(ds[ind1][1])
                        








View More Similar Problems

Direct Connections

Enter-View ( EV ) is a linear, street-like country. By linear, we mean all the cities of the country are placed on a single straight line - the x -axis. Thus every city's position can be defined by a single coordinate, xi, the distance from the left borderline of the country. You can treat all cities as single points. Unfortunately, the dictator of telecommunication of EV (Mr. S. Treat Jr.) do

View Solution →

Subsequence Weighting

A subsequence of a sequence is a sequence which is obtained by deleting zero or more elements from the sequence. You are given a sequence A in which every element is a pair of integers i.e A = [(a1, w1), (a2, w2),..., (aN, wN)]. For a subseqence B = [(b1, v1), (b2, v2), ...., (bM, vM)] of the given sequence : We call it increasing if for every i (1 <= i < M ) , bi < bi+1. Weight(B) =

View Solution →

Kindergarten Adventures

Meera teaches a class of n students, and every day in her classroom is an adventure. Today is drawing day! The students are sitting around a round table, and they are numbered from 1 to n in the clockwise direction. This means that the students are numbered 1, 2, 3, . . . , n-1, n, and students 1 and n are sitting next to each other. After letting the students draw for a certain period of ti

View Solution →

Mr. X and His Shots

A cricket match is going to be held. The field is represented by a 1D plane. A cricketer, Mr. X has N favorite shots. Each shot has a particular range. The range of the ith shot is from Ai to Bi. That means his favorite shot can be anywhere in this range. Each player on the opposite team can field only in a particular range. Player i can field from Ci to Di. You are given the N favorite shots of M

View Solution →

Jim and the Skyscrapers

Jim has invented a new flying object called HZ42. HZ42 is like a broom and can only fly horizontally, independent of the environment. One day, Jim started his flight from Dubai's highest skyscraper, traveled some distance and landed on another skyscraper of same height! So much fun! But unfortunately, new skyscrapers have been built recently. Let us describe the problem in one dimensional space

View Solution →

Palindromic Subsets

Consider a lowercase English alphabetic letter character denoted by c. A shift operation on some c turns it into the next letter in the alphabet. For example, and ,shift(a) = b , shift(e) = f, shift(z) = a . Given a zero-indexed string, s, of n lowercase letters, perform q queries on s where each query takes one of the following two forms: 1 i j t: All letters in the inclusive range from i t

View Solution →