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
Binary Search Tree : Lowest Common Ancestor
You are given pointer to the root of the binary search tree and two values v1 and v2. You need to return the lowest common ancestor (LCA) of v1 and v2 in the binary search tree. In the diagram above, the lowest common ancestor of the nodes 4 and 6 is the node 3. Node 3 is the lowest node which has nodes and as descendants. Function Description Complete the function lca in the editor b
View Solution →Swap Nodes [Algo]
A binary tree is a tree which is characterized by one of the following properties: It can be empty (null). It contains a root node only. It contains a root node with a left subtree, a right subtree, or both. These subtrees are also binary trees. In-order traversal is performed as Traverse the left subtree. Visit root. Traverse the right subtree. For this in-order traversal, start from
View Solution →Kitty's Calculations on a Tree
Kitty has a tree, T , consisting of n nodes where each node is uniquely labeled from 1 to n . Her friend Alex gave her q sets, where each set contains k distinct nodes. Kitty needs to calculate the following expression on each set: where: { u ,v } denotes an unordered pair of nodes belonging to the set. dist(u , v) denotes the number of edges on the unique (shortest) path between nodes a
View Solution →Is This a Binary Search Tree?
For the purposes of this challenge, we define a binary tree to be a binary search tree with the following ordering requirements: The data value of every node in a node's left subtree is less than the data value of that node. The data value of every node in a node's right subtree is greater than the data value of that node. Given the root node of a binary tree, can you determine if it's also a
View Solution →Square-Ten Tree
The square-ten tree decomposition of an array is defined as follows: The lowest () level of the square-ten tree consists of single array elements in their natural order. The level (starting from ) of the square-ten tree consists of subsequent array subsegments of length in their natural order. Thus, the level contains subsegments of length , the level contains subsegments of length , the
View Solution →Balanced Forest
Greg has a tree of nodes containing integer data. He wants to insert a node with some non-zero integer value somewhere into the tree. His goal is to be able to cut two edges and have the values of each of the three new trees sum to the same amount. This is called a balanced forest. Being frugal, the data value he inserts should be minimal. Determine the minimal amount that a new node can have to a
View Solution →