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>();
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();
elements[e-1].setId = set1;
}
s2.sets.clear();
}
else{
Iterator<Integer> iterator = s1.sets.iterator();
while (iterator.hasNext()){
Integer e = iterator.next();
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()
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))

Jim and the Skyscrapers

Jim has invented a new flying object called HZ42. HZ42 is like a broom and can only fly horizontally, independent of the environment. One day, Jim started his flight from Dubai's highest skyscraper, traveled some distance and landed on another skyscraper of same height! So much fun! But unfortunately, new skyscrapers have been built recently. Let us describe the problem in one dimensional space

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

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

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

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

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