Components in a graph


Problem Statement :


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 value will always be connected to at least 1 other node.

Note Single nodes should not be considered in the answer.


Function Description
Complete the connectedComponents function in the editor below.

connectedComponents has the following parameter(s):
- int bg[n][2]: a 2-d array of integers that represent node ends of graph edges

Returns
- int[2]: an array with 2 integers, the smallest and largest component sizes

Input Format

The first line contains an integer n, the size of bg.
Each of the next n lines contain two space-separated integers, bg[ i ][ 0 ] and . bg[ i ][ 1 ]



Solution :



title-img


                            Solution in C :

In C ++ :





#include<bits/stdc++.h>
#include<fstream>
using namespace std;
int t, n, m, i, j, parent[30005], sum[30005], ans,ans1;
int a, b;
int find(int x)
{
    if (x == parent[x])
        return parent[x];
    else
        return parent[x]=find(parent[x]);
}
int main()
{
        //ifstream inp;
        //ofstream out;
        ans = 2,ans1=200000000;
        cin>>n;
        assert(n<=15000);
        for (i = 1; i <= 2*n; i ++)
        {
            parent[i] = i;
            sum[i] = 1;
        }
        for (i = 0; i < n; i++)
        {
            cin>>a>>b;
            assert(a<=n&&a>=1);
            assert(b>=(n+1)&&b<=2*n);
            int pa = find(a);
            int pb = find(b);
            if (pa != pb)
            {
                parent[pa] = pb;
                sum[pb] += sum[pa];
            }
        }
        for (i = 1; i <= 2*n; i ++)
        {
            if(sum[i]!=1){
            int ind=find(i);
            ans1=min(sum[ind],ans1);
            }
        }
        for (i = 1; i <= 2*n; i ++)
        {
            if(sum[i]!=1){
            int ind1=find(i);
            ans=max(sum[ind1],ans);
            }
        }
        cout<<ans1<<" "<<ans<<endl;

        //printf("%d\n", ans);
    return 0;
}








In Java :





import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

class Element{
    int elementId;
    int setId;
}

class Set{
    int setId;
    HashSet<Integer> sets;
}

public class Solution {

    Element [] elements;
    Set []sets;
    void input(){
        Scanner sin = new Scanner(System.in);
        int N = sin.nextInt();
        elements = new Element[2*N];
        sets = new Set[2*N];
        for(int i = 1; i <= 2*N; i++){
            Element e = new Element();
            e.elementId = i;
            e.setId = i;
            elements[i-1] = e;
            Set s = new Set();
            s.setId = i;
            s.sets = new HashSet<Integer>();
            s.sets.add(i);
            sets[i-1] = s;
        }
        
        for(int i = 0; i < N; i++){
            int g1 = sin.nextInt();
            int b1 = sin.nextInt();
            union(g1,b1);
        }
        int min = 15001;
        int max = 0;
        for(int i = 0; i < 2*N; i++){
            //System.out.println(sets[i].sets.size());
            if(sets[i].sets.size() > 1 && sets[i].sets.size() < min){
                min = sets[i].sets.size();
            }
            if(sets[i].sets.size() > max){
                max = sets[i].sets.size();
            }
        }
        System.out.println(min+" "+max);
    }
    
    void union(int g1, int b1){
        if(find(g1,b1)){
            
        }
        else{
            int set1 = elements[g1-1].setId;
            int set2 = elements[b1-1].setId;
            Set s1 = sets[set1-1];
            Set s2 = sets[set2-1];
            if(s1.sets.size() > s2.sets.size()){
                Iterator<Integer> iterator = s2.sets.iterator();
                while (iterator.hasNext()){
                    Integer e = iterator.next();
                    s1.sets.add(e);
                    elements[e-1].setId = set1;
                }
                s2.sets.clear();
            }
            else{
                Iterator<Integer> iterator = s1.sets.iterator();
                while (iterator.hasNext()){
                    Integer e = iterator.next();
                    s2.sets.add(e);
                    elements[e-1].setId = set2;
                }
                s1.sets.clear();                
            }
        }
    }
    
    boolean find(int g1,int b1){
        
        if(elements[g1-1].setId == elements[b1-1].setId){
            return true;
        }
        else{
            return false;
        }
    }
    
    public static void main(String[] args) {
        Solution s = new Solution();
        s.input();
    }
}








In C :





#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdint.h>
//int16_t arr[30010][15010];
int16_t **arr;
int n;
int8_t tmp[30010];
int16_t cnt[30010];
int16_t inp[30010][2];
int d, min, max;
void scan(int k)
{
    int i;
    for (i = 1; i <= arr[k][0]; i++) {
        if (tmp[arr[k][i]] == 0) {
            tmp[arr[k][i]] = 1;
            d++;
            scan(arr[k][i]);
        }
    }
}

int main() {
    int i, j, a, b;
    scanf("%d", &n);
    
    
    
    arr = (int16_t **) calloc(1, (2 * n + 1) * sizeof(int16_t *));
    if (arr == NULL)
        return -1;
    for(i = 0; i < n; i++) {
        scanf("%d%d", &inp[i][0], &inp[i][1]);
        cnt[inp[i][0]]++;
        cnt[inp[i][1]]++;
    }
    
    for(i = 1; i <= 2*n; i++) {
        arr[i] = (int16_t *) calloc(1, (cnt[i]+1)*sizeof(int16_t));
        if (arr[i] == NULL)
            return -1;
    }
    
    /*
    for(i = 1; i <= 2*n; i++) {
        for(j = 0; j <= n; j++) {
            printf("%d ", arr[i][j]);
        }
        printf("\n");
    }
    */
  //  return 0;
    for(i = 0; i < n; i++) {
        //scanf("%d%d", &a, &b);
        a=inp[i][0];
        b=inp[i][1];
        if (arr[a] == NULL) {
            arr[a] = (int16_t *) calloc(1, (n+1)*sizeof(int16_t));
            if (arr[a] == NULL)
                return -1;
        }
        if (arr[b] == NULL) {
            arr[b] = (int16_t *) calloc(1, (n+1)*sizeof(int16_t));
            if (arr[b] == NULL)
                return -1;
        }       
        arr[a][0]++;
        arr[a][arr[a][0]] = b;
        arr[b][0]++;
        arr[b][arr[b][0]] = a;
    }
    //return 0;
    /*
    for(i = 1; i <= 2*n; i++) {
        for(j = 0; j <= n; j++) {
            printf("%d ", arr[i][j]);
        }
        printf("\n");
    }
    return 0;
    */
    /*
    for(i = 1; i <= n; i++) {
        if (arr[i] == NULL)
            continue;
        printf("%d -> ", i);
        for (j = 1; j <= arr[i][0]; j++) {
            printf("%d ", arr[i][j]);
        }
        printf("\n");
    }
    */
    min = 2000000000;
    max = -1;
    for(i = 1; i <= n; i++) {
        d = 0;
        if (tmp[i] == 0) {
         //   printf("%d -> ", i);
            if (arr[i])
                scan(i);
         //   printf("%d\n", d);
        }
        if (d < min && d != 0)
            min = d;
        if (d > max)
            max = d;
    }
    printf("%d %d\n", min, max);
 
    return 0;
}








In Python3 :





from collections import deque, defaultdict

def bfs(g, s):
    visited = set()
    q = deque([s])
    
    while q:
        v = q.popleft()
        visited.add(v)
        for adj in g[v]:
            if adj not in visited and adj not in q:
                q.append(adj)
    return visited
        
def con_components(g):
    visited = set()
    components = []
    for s in g.keys():
        if s not in visited:
            nodes = bfs(g, s)
            visited |= nodes
            components.append(nodes)
    return components

if __name__ == '__main__':
    n = int(input())
    g = defaultdict(list)
    for _ in range(n):
        a,b = map(int, input().split())
        g[a].append(b)
        g[b].append(a)
    c = con_components(g)
    lens = list(map(len, c))
    print(min(lens), max(lens))
                        








View More Similar Problems

Tree Coordinates

We consider metric space to be a pair, , where is a set and such that the following conditions hold: where is the distance between points and . Let's define the product of two metric spaces, , to be such that: , where , . So, it follows logically that is also a metric space. We then define squared metric space, , to be the product of a metric space multiplied with itself: . For

View Solution →

Array Pairs

Consider an array of n integers, A = [ a1, a2, . . . . an] . Find and print the total number of (i , j) pairs such that ai * aj <= max(ai, ai+1, . . . aj) where i < j. Input Format The first line contains an integer, n , denoting the number of elements in the array. The second line consists of n space-separated integers describing the respective values of a1, a2 , . . . an .

View Solution →

Self Balancing Tree

An AVL tree (Georgy Adelson-Velsky and Landis' tree, named after the inventors) is a self-balancing binary search tree. In an AVL tree, the heights of the two child subtrees of any node differ by at most one; if at any time they differ by more than one, rebalancing is done to restore this property. We define balance factor for each node as : balanceFactor = height(left subtree) - height(righ

View Solution →

Array and simple queries

Given two numbers N and M. N indicates the number of elements in the array A[](1-indexed) and M indicates number of queries. You need to perform two types of queries on the array A[] . You are given queries. Queries can be of two types, type 1 and type 2. Type 1 queries are represented as 1 i j : Modify the given array by removing elements from i to j and adding them to the front. Ty

View Solution →

Median Updates

The median M of numbers is defined as the middle number after sorting them in order if M is odd. Or it is the average of the middle two numbers if M is even. You start with an empty number list. Then, you can add numbers to the list, or remove existing numbers from it. After each add or remove operation, output the median. Input: The first line is an integer, N , that indicates the number o

View Solution →

Maximum Element

You have an empty sequence, and you will be given N queries. Each query is one of these three types: 1 x -Push the element x into the stack. 2 -Delete the element present at the top of the stack. 3 -Print the maximum element in the stack. Input Format The first line of input contains an integer, N . The next N lines each contain an above mentioned query. (It is guaranteed that each

View Solution →