Friend Circle Queries


Problem Statement :


The population of HackerWorld is 10 ^ 9. Initially, none of the people are friends with each other. In order to start a friendship, two persons a and b  have to shake hands, where 1 <= a, b <= 10^9. The friendship relation is transitive, that is if a and b shake hands with each other, a and friends of a become friends with  b and friends of b.

You will be given q  queries. After each query, you need to report the size of the largest friend circle (the largest group of friends) formed after considering that query.

For example, your list of queries is:


Function Description

Complete the function maxCircle in the editor below. It must return an array of integers representing the size of the maximum circle of friends after each query.

maxCircle has the following parameter(s):

queries: an array of integer arrays, each with two elements indicating a new friendship
Input Format

The first line contains an integer, q, the number of queries to process.
Each of the next q lines consists of two space-separated integers denoting the 2-D array querries.



Output Format

Return an integer array of size q, whose value at index i is the size of largest group present after ith processing the  query.



Solution :



title-img




                        Solution in C++ :

In  C  ++  :








#include<bits/stdc++.h>
using namespace std;

const int MAX=500005;

int a[MAX], s[MAX];
set<int> sz;

void init(int n)
{
	for(int i=0;i<n;i++)
	{
		a[i]=i;
		s[i]=1;
	}
}

int root(int x)
{
	while(a[x]!=x)
	{
		a[x]=a[a[x]];
		x=a[x];
	}
	return x;
}

void join(int x,int y)
{
	int rx=root(x);
	int ry=root(y);
	if(rx==ry)
		return;
	if(s[rx]>s[ry])
	{
		s[rx]+=s[ry];
		a[ry]=rx;
		sz.insert(-s[rx]);
	}
	else
	{
		s[ry]+=s[rx];
		a[rx]=ry;
		sz.insert(-s[ry]);
	}
}

int main()
{
	int q;
	vector<pair<int,int> > queries;
	map<int,int> m;
	vector<int> aux;

	scanf("%d",&q);
	
	for(int i=0;i<q;i++)
	{
		int x,y;
		scanf("%d%d",&x,&y);
		queries.push_back(make_pair(x,y));
		aux.push_back(x);
		aux.push_back(y);
	}
	sort(aux.begin(),aux.end());
	int curr=1;
	for(int i=0;i<aux.size();i++)
	{
		if(i==0||aux[i]!=aux[i-1])
		{
			m[aux[i]]=curr++;
		}
	}
	for(int i=0;i<q;i++)
	{
		queries[i].first=m[queries[i].first];
		queries[i].second=m[queries[i].second];
	}

	init(curr);

	for(int i=0;i<q;i++)
	{
		join(queries[i].first,queries[i].second);
		printf("%d\n",-*(sz.begin()));
	}
	return 0;
}
                    


                        Solution in Java :

In    Java : 




public class Solution {
  public static class DisjointSet {
    private static Map<Integer,Node> map = new HashMap<>();
    private static int max = 0; 
    static class Node {
      long data;
      Node parent;
      int rank;
    }
    public static void makeSet(int data) {
      Node node = new Node();
      node.data = data;
      node.parent = node;
      node.rank = 1;
      map.put(data, node);
    }
    public static boolean union(int data1, int data2) {
        Node node1 = map.get(data1);
        Node node2 = map.get(data2);
        Node parent1 = findSet(node1);
        Node parent2 = findSet(node2);
        if (parent1.data == parent2.data) {
            return false;
        }
        if (parent1.rank >= parent2.rank) {
            parent1.rank = parent1.rank + parent2.rank;
            parent2.parent = parent1;
            max = Math.max(max,parent1.rank);
        } else {
            parent2.rank = parent2.rank+parent1.rank;
            parent1.parent = parent2;
            max = Math.max(max,parent2.rank); 
        }
        return true;
    }
    public static long findSet(int data) {
        return findSet(map.get(data)).data;
    }
    private static Node findSet(Node node) {
        Node parent = node.parent;
        if (parent == node) {
            return parent;
        }
        node.parent = findSet(node.parent);
        return node.parent;
    }
    
}

    static int[] maxCircle(int[][] queries) {
      DisjointSet ds = new DisjointSet();
      int[] arr = new int[queries.length]; 
      for(int[] a : queries) {
        ds.makeSet(a[0]);
        ds.makeSet(a[1]); 
      }

      int i = 0;
      for(int[] a : queries) {
        ds.union(a[0], a[1]); 
        arr[i] = ds.max;
        i++;
      }
      return arr;
    }
                    


                        Solution in Python : 
                            
In   Python3  :







def init_cmp(mp,x,y):
    if x not in mp:
        mp[x]=x
    if y not in mp:
        mp[y]=y

def init_cc(cc,x,y):
    if x not in cc:
        cc[x]=1
    if y not in cc:
        cc[y]=1

def get_parent(mp,x):
    while mp[x]!=x:
        x=mp[x]
    return x

# Complete the maxCircle function below.
def maxCircle(queries):
    mp = {}
    cc = {}
    max_gp = 0
    res = []
    for q in queries:
        init_cmp(mp,q[0],q[1])
        init_cc(cc,q[0],q[1])
        p1 = get_parent(mp,q[0])
        p2 = get_parent(mp,q[1])
        if p1!=p2:
            if cc[p1]>cc[p2]:
                mp[p2]=p1
                cc[p1]=cc[p1]+cc[p2]
            else:
                mp[p1]=p2
                cc[p2]=cc[p1]+cc[p2]
            max_gp = max(max_gp,max(cc[p1],cc[p2]))
        res.append(max_gp)
    return res
                    


View More Similar Problems

Contacts

We're going to make our own Contacts application! The application must perform two types of operations: 1 . add name, where name is a string denoting a contact name. This must store name as a new contact in the application. find partial, where partial is a string denoting a partial name to search the application for. It must count the number of contacts starting partial with and print the co

View Solution →

No Prefix Set

There is a given list of strings where each string contains only lowercase letters from a - j, inclusive. The set of strings is said to be a GOOD SET if no string is a prefix of another string. In this case, print GOOD SET. Otherwise, print BAD SET on the first line followed by the string being checked. Note If two strings are identical, they are prefixes of each other. Function Descriptio

View Solution →

Cube Summation

You are given a 3-D Matrix in which each block contains 0 initially. The first block is defined by the coordinate (1,1,1) and the last block is defined by the coordinate (N,N,N). There are two types of queries. UPDATE x y z W updates the value of block (x,y,z) to W. QUERY x1 y1 z1 x2 y2 z2 calculates the sum of the value of blocks whose x coordinate is between x1 and x2 (inclusive), y coor

View Solution →

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 →