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 :
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
Largest Rectangle
Skyline Real Estate Developers is planning to demolish a number of old, unoccupied buildings and construct a shopping mall in their place. Your task is to find the largest solid area in which the mall can be constructed. There are a number of buildings in a certain two-dimensional landscape. Each building has a height, given by . If you join adjacent buildings, they will form a solid rectangle
View Solution →Simple Text Editor
In this challenge, you must implement a simple text editor. Initially, your editor contains an empty string, S. You must perform Q operations of the following 4 types: 1. append(W) - Append W string to the end of S. 2 . delete( k ) - Delete the last k characters of S. 3 .print( k ) - Print the kth character of S. 4 . undo( ) - Undo the last (not previously undone) operation of type 1 or 2,
View Solution →Poisonous Plants
There are a number of plants in a garden. Each of the plants has been treated with some amount of pesticide. After each day, if any plant has more pesticide than the plant on its left, being weaker than the left one, it dies. You are given the initial values of the pesticide in each of the plants. Determine the number of days after which no plant dies, i.e. the time after which there is no plan
View Solution →AND xor OR
Given an array of distinct elements. Let and be the smallest and the next smallest element in the interval where . . where , are the bitwise operators , and respectively. Your task is to find the maximum possible value of . Input Format First line contains integer N. Second line contains N integers, representing elements of the array A[] . Output Format Print the value
View Solution →Waiter
You are a waiter at a party. There is a pile of numbered plates. Create an empty answers array. At each iteration, i, remove each plate from the top of the stack in order. Determine if the number on the plate is evenly divisible ith the prime number. If it is, stack it in pile Bi. Otherwise, stack it in stack Ai. Store the values Bi in from top to bottom in answers. In the next iteration, do the
View Solution →Queue using Two Stacks
A queue is an abstract data type that maintains the order in which elements were added to it, allowing the oldest elements to be removed from the front and new elements to be added to the rear. This is called a First-In-First-Out (FIFO) data structure because the first element added to the queue (i.e., the one that has been waiting the longest) is always the first one to be removed. A basic que
View Solution →