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

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 →

Counting On a Tree

Taylor loves trees, and this new challenge has him stumped! Consider a tree, t, consisting of n nodes. Each node is numbered from 1 to n, and each node i has an integer, ci, attached to it. A query on tree t takes the form w x y z. To process a query, you must print the count of ordered pairs of integers ( i , j ) such that the following four conditions are all satisfied: the path from n

View Solution →

Polynomial Division

Consider a sequence, c0, c1, . . . , cn-1 , and a polynomial of degree 1 defined as Q(x ) = a * x + b. You must perform q queries on the sequence, where each query is one of the following two types: 1 i x: Replace ci with x. 2 l r: Consider the polynomial and determine whether is divisible by over the field , where . In other words, check if there exists a polynomial with integer coefficie

View Solution →

Costly Intervals

Given an array, your goal is to find, for each element, the largest subarray containing it whose cost is at least k. Specifically, let A = [A1, A2, . . . , An ] be an array of length n, and let be the subarray from index l to index r. Also, Let MAX( l, r ) be the largest number in Al. . . r. Let MIN( l, r ) be the smallest number in Al . . .r . Let OR( l , r ) be the bitwise OR of the

View Solution →

The Strange Function

One of the most important skills a programmer needs to learn early on is the ability to pose a problem in an abstract way. This skill is important not just for researchers but also in applied fields like software engineering and web development. You are able to solve most of a problem, except for one last subproblem, which you have posed in an abstract way as follows: Given an array consisting

View Solution →

Self-Driving Bus

Treeland is a country with n cities and n - 1 roads. There is exactly one path between any two cities. The ruler of Treeland wants to implement a self-driving bus system and asks tree-loving Alex to plan the bus routes. Alex decides that each route must contain a subset of connected cities; a subset of cities is connected if the following two conditions are true: There is a path between ever

View Solution →