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

Minimum Average Waiting Time

Tieu owns a pizza restaurant and he manages it in his own way. While in a normal restaurant, a customer is served by following the first-come, first-served rule, Tieu simply minimizes the average waiting time of his customers. So he gets to decide who is served first, regardless of how sooner or later a person comes. Different kinds of pizzas take different amounts of time to cook. Also, once h

View Solution →

Merging Communities

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 w

View Solution →

Components in a graph

There are 2 * N nodes in an undirected graph, and a number of edges connecting some nodes. In each edge, the first value will be between 1 and N, inclusive. The second node will be between N + 1 and , 2 * N inclusive. Given a list of edges, determine the size of the smallest and largest connected components that have or more nodes. A node can have any number of connections. The highest node valu

View Solution →

Kundu and Tree

Kundu is true tree lover. Tree is a connected graph having N vertices and N-1 edges. Today when he got a tree, he colored each edge with one of either red(r) or black(b) color. He is interested in knowing how many triplets(a,b,c) of vertices are there , such that, there is atleast one edge having red color on all the three paths i.e. from vertex a to b, vertex b to c and vertex c to a . Note that

View Solution →

Super Maximum Cost Queries

Victoria has a tree, T , consisting of N nodes numbered from 1 to N. Each edge from node Ui to Vi in tree T has an integer weight, Wi. Let's define the cost, C, of a path from some node X to some other node Y as the maximum weight ( W ) for any edge in the unique path from node X to Y node . Victoria wants your help processing Q queries on tree T, where each query contains 2 integers, L and

View Solution →

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 →