0% found this document useful (0 votes)
9 views

Cpunit V

Uploaded by

Sai someone
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

Cpunit V

Uploaded by

Sai someone
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 23

COMPETITIVE PROGRAMMING UNIT-V III – II SEM (KR21 Regulations)

SYLLABUS:
Disjoint Set Union: Disjoint set and its operations, Union Find Algorithm, Lexicographically
Smallest Equivalent String, Number of Distinct Islands, and Number of Connected
Components in an Undirected Graph.

Introduction:

Disjoint sets in mathematics are two sets that don't have any element in common. Sets
can contain any number of elements, and those elements can be of any type. We can have a
set of cars, a set of integers, a set of colors, etc. Sets also have various operations that can be
performed on them, such as union, intersection, difference, etc.

We focus on Disjoint Set Data Structure and the operations we can perform. we will
go through what a disjoint set data structure is, the disjoint set operations, as well as
examples.

Disjoint Set Data Structure:

Before we look at disjoint set operations, let us understand what the disjoint set data
structure itself is.

A disjoint set data structure is a data structure that stores a list of disjoint sets. In other words,
this data structure divides a set into multiple subsets - such that no 2 subsets contain any
common element. They are also called union-find data structures or merge-find sets.

Example: if the initial set is [1,2,3,4,5,6,7,8].

A Disjoint Set Data Structure might partition it as - [(1,2,4), (3,5), (6,8),(7)].

This contains all of the elements of the original set, and no 2 subsets have any element in
common.

The following partitions would be invalid:

[(1,2,3),(3,4,5),(6,8),(7)] - invalid because 3 occurs in 2 subsets.

[(1,2,3),(5,6),(7,8)] -invalid as 4 is missing.

KESHAV MEMORIAL INSTITUTE OF TECHNOLOGY (AN AUTONOMOUS INSTITUTE)


COMPETITIVE PROGRAMMING UNIT-V III – II SEM (KR21 Regulations)

Representative Member

Each subset in a Disjoint Set Data Structure has a representative member. More
commonly, we call this the parent. This is simply the member responsible for identifying the
subset.

Let's understand this with an example.


Suppose this is the partitioning of sets in our Disjoint Set Data structure.

We wish to identify each subset, so we assign each subset a value by which we can identify
it. The easiest way to do this is to choose a member of the subset and make it
the representative member. This representative member will become the parent of all
values in the subset.

Here, we have assigned representative members to each subset. Thus, if we wish to know
which subset 3 is a part of, we can simply say - 3 is a part of the subset with representative
member 1. More simply, we can say that the parent of 3 is 1.

Here, 1 is its own parent.

KESHAV MEMORIAL INSTITUTE OF TECHNOLOGY (AN AUTONOMOUS INSTITUTE)


COMPETITIVE PROGRAMMING UNIT-V III – II SEM (KR21 Regulations)

Disjoint Set Operations:

There are 2 major disjoint set operations:


1. Union/Merge - this is used to merge 2 subsets into a single subset.
2. Find - This is used to find which subset a particular value belongs to.

We will take a look at both of them. To make things easier, we will change our sets from
integers to Cities.

Let's say this data structure represents the places connected via express trains/ metro lines or
any other means.

Union/Merge:

Suppose, in our example - a new express train started from Delhi to Agra. This would
mean that all the cities connected to Delhi are now connected to all the cities connected to
Agra.
This simply means that we can merge the subsets of Agra and Delhi into a single subset. It
will look like this.

One key issue here is which out of Agra and Delhi will be the new Parent? For now, we will
just choose any of them, as it will be sufficient for our purposes. Let's take Delhi for now.

Further optimizations can be made to this by choosing the parent based on which subset
has a larger number of values.

KESHAV MEMORIAL INSTITUTE OF TECHNOLOGY (AN AUTONOMOUS INSTITUTE)


COMPETITIVE PROGRAMMING UNIT-V III – II SEM (KR21 Regulations)

 This is the new state of our Disjoint Set Data Structure. Delhi is the parent of Delhi,
Gurgaon, Noida, Agra, Vrindavan, and Mathura.
 This would mean that we would have to change the parent of Agra, Vrindavan, and
Mathura (basically, all the children of Agra), to Delhi.
 This would be linear in time. If we perform the union operation m times, and each union
takes O(n) times, we would get a quadratic O(mn) time complexity. This is not optimized
enough.
Instead, we structure it like this:

Earlier, Agra was its own parent. Now, Delhi is the parent of Agra.
Now, you might be wondering - The parent of Vrindavan is still Agra. It should have been
Delhi now.
This is where the next operation helps us - the find operation.

Find:
The find operation helps us find the parent of a node. As we saw above, the direct
parent of a node might not be its actual (logical) parent. E.g., the logical parent of Vrindavan
should be Delhi in the above example. But its direct parent is Agra.

So, how do we find the actual parent?

The find operation helps us to find the actual parent. In pseudocode, the find operation looks
like this:

KESHAV MEMORIAL INSTITUTE OF TECHNOLOGY (AN AUTONOMOUS INSTITUTE)


COMPETITIVE PROGRAMMING UNIT-V III – II SEM (KR21 Regulations)

find(node):
if (parent(node)==node) return node;
else return find(parent(node));

We don't return the direct parent of the node. We keep going up the tree of parents until we
find a node that is its own parent.
Let's understand this via our example.

Suppose we have to find the parent of Mathura.


1. Check the direct parent of Mathura. It's Agra. Is Agra == Mathura?
The answer is false. So, now we call the find operation on Agra.
2. Check the direct parent of Agra. It's Delhi. Is Delhi ==Agra?
The answer is false. So now we call the find operation on Delhi.
3. Check the direct parent of Delhi. It's Delhi. Is Delhi==Delhi.
The answer is true! So, our final answer for the parent of Mathura is Delhi.
This way, we keep going "up" the tree until we reach a root element. A root element is a node
with its own parent - in our case, Delhi.

KESHAV MEMORIAL INSTITUTE OF TECHNOLOGY (AN AUTONOMOUS INSTITUTE)


COMPETITIVE PROGRAMMING UNIT-V III – II SEM (KR21 Regulations)

Example:

Let's try to find the parent of K in this example. (A and D are their own parents)
1. ParentOf(K) is I. Is I == K?
False. So, we move upward, now using I.
2. ParentOf(I) is C. Is C== I?
False. Move upward using C.
3. ParentOf(C) is A. Is A==C?
False. Move upward using A.
4. ParentOf(A) is A. Is A==A?
True! Our final answer is A.
Let's understand the use of a Disjoint Set Data Structure through a simple application -
Finding a cycle in an undirected graph.

Find a Cycle in an Undirected Graph using Disjoint Set Data Structure:

Let us understand the disjoint set operations in daa more clearly with the help of an
example. Here, we will use a disjoint set data structure to find whether an undirected graph
contains a cycle or not. We are assuming that our graph does not contain any self-loops.

KESHAV MEMORIAL INSTITUTE OF TECHNOLOGY (AN AUTONOMOUS INSTITUTE)


COMPETITIVE PROGRAMMING UNIT-V III – II SEM (KR21 Regulations)

Let this be our graph. Each node is initialized as its own parent. The list of edges is shown on
the top right, and the parents are shown at the bottom. We have shown each edge only once
for simplicity (i.e., 1-2 and 2-1 aren't shown separately)

Algorithm:

We will go through each edge and do the following. Let the edge be u-v.
1. Find the parent of u and v. If both parents are the same, it means u and v are part of the
same subset, and we have found a cycle.v
2. If they are not the same, merge u and v. We don't merge u and v directly. Instead, we
merge the parents of u and v. This ensures that all the siblings of u and all the siblings of
v have the same common parent.
We do this for all edges.

Walkthrough

1. 1-2 Edge.
Parent of 1 is 1, parent of 2 is 2. They are different, so we will merge them. Set the parent of
2 as 1 (this is chosen randomly, setting the parent of 1 as 2 would also have been correct ).

2. 1-4 Edge.
Parent of 1 is 1. Parent of 4 is 4. They are not the same, so merge 1 and 4. Set parent
of 4 as 1.

KESHAV MEMORIAL INSTITUTE OF TECHNOLOGY (AN AUTONOMOUS INSTITUTE)


COMPETITIVE PROGRAMMING UNIT-V III – II SEM (KR21 Regulations)

3. 2-5 Edge.
The parent of 2 is 1, and the parent of 5 is 5. They aren't the same, so we'll merge them. Set
the parent of 5 as 1.

4. 3-6 Edge.
The parent of 3 is 3, and the parent of 6 is 6. They aren't the same, so we'll merge them. Set
the parent of 6 as 3.

KESHAV MEMORIAL INSTITUTE OF TECHNOLOGY (AN AUTONOMOUS INSTITUTE)


COMPETITIVE PROGRAMMING UNIT-V III – II SEM (KR21 Regulations)

5. 5-6 Edge.
The parent of 5 is 1, and the parent of 6 is 3. They aren't the same, so we'll merge them. Set
the parent of 3 as 1.

Note here - the direct parent of 6 is still 3. But, the actual parent becomes 1, because the
parent of 3 is 1. (The dotted line is not an edge in the graph, it shows that the parent of 3 is 1)

6. 6-2 Edge.
The parent of 6 is 1 (actual parent), and the parent of 2 is also 1. These are both the
same. Thus, our graph contains a cycle.

Complexities for Disjoint Set Operations

 The space complexity is O(n), where n is the number of vertices. The parent array stores
the parent of each vertex. Hence we get O(n) space complexity. We aren't considering the
space complexity of the graph in this because the graph is the input here.

 The time complexity is O(log N) in the average case because the find operation will have
to go up a tree with n nodes. The height of a tree in the average case will be log N. In the
worst case, we can have a skewed tree, and our time complexity will become O(n).

KESHAV MEMORIAL INSTITUTE OF TECHNOLOGY (AN AUTONOMOUS INSTITUTE)


COMPETITIVE PROGRAMMING UNIT-V III – II SEM (KR21 Regulations)

Weighted Rule for Union (i,j):

 If the number of nodes in the tree with root i is less than the number in the tree
with root j, then make j the parent of i ; otherwise make i the parent of j.

Pseudo code

Array-Representation:

KESHAV MEMORIAL INSTITUTE OF TECHNOLOGY (AN AUTONOMOUS INSTITUTE)


COMPETITIVE PROGRAMMING UNIT-V III – II SEM (KR21 Regulations)

Collapsing Rule(finding an element):

 If j is a node on the path from i to its root and parent[i]≠ root(i), then set parent[j] to
root(i).
 The first run of find operation will collapse the tree. Therefore, all following find
operation of the same element only goes up one link to find the root.
Pseudo code:

KESHAV MEMORIAL INSTITUTE OF TECHNOLOGY (AN AUTONOMOUS INSTITUTE)


COMPETITIVE PROGRAMMING UNIT-V III – II SEM (KR21 Regulations)

Applications:
1. Lexicographically Smallest Equivalent String.
2. Number of Distinct Islands.
3. Number of Connected Components in an Undirected Graph.

1. Lexicographically Smallest Equivalent String:

You are given two strings of the same length s1 and s2 and a string baseStr.
We say s1[i] and s2[i] are equivalent characters.

For example, if s1 = "abc" and s2 = "cde", then we have 'a' == 'c', 'b' == 'd', and 'c' == 'e'.
Equivalent characters follow the usual rules of any equivalence relation:
Reflexivity: 'a' == 'a'.
Symmetry: 'a' == 'b' implies 'b' == 'a'.
Transitivity: 'a' == 'b' and 'b' == 'c' implies 'a' == 'c'.

For example, given the equivalency information from s1 = "abc" and s2 = "cde", "acd"
and "aab"
are equivalent strings of baseStr = "eed", and "aab" is the lexicographically smallest
equivalent string of baseStr.
Return the lexicographically smallest equivalent string of baseStr by using the
equivalency information from s1 and s2.

Example 1:
Input: s1 = "parker", s2 = "morris", baseStr = "parser"
Output: "makkek"
Explanation: Based on the equivalency information in s1 and s2, we can group their
characters as [m,p], [a,o], [k,r,s], [e,i].
The characters in each group are equivalent and sorted in lexicographical order.
So the answer is "makkek".

Example 2:
Input: s1 = "hello", s2 = "world", baseStr = "hold"
Output: "hdld"
Explanation: Based on the equivalency information in s1 and s2, we can group their
characters as [h,w], [d,e,o], [l,r].
So only the second letter 'o' in baseStr is changed to 'd', the answer is "hdld".

Example 3:
Input: s1 = "leetcode", s2 = "programs", baseStr = "sourcecode"
Output: "aauaaaaada"
Explanation: We group the equivalent characters in s1 and s2 as [a,o,e,r,s,c], [l,p], [g,t]
and [d,m], thus all letters in baseStr except 'u' and 'd' are transformed to 'a',
the answer is "aauaaaaada".

KESHAV MEMORIAL INSTITUTE OF TECHNOLOGY (AN AUTONOMOUS INSTITUTE)


COMPETITIVE PROGRAMMING UNIT-V III – II SEM (KR21 Regulations)

APPROACH:

 The idea here is to use disjoint set union or union-find data structure.
 It provides the following capabilities. We are given several elements, each of which is
a separate set. A DSU will have an operation to combine any two sets, and it will be
able to tell in which set a specific element is.
 Thus the basic interface of this data structure consists of only three operations:
 union_sets(a, b) - merges the two specified sets (the set in which the element a is
located, and the set in which the element b is located), as we need the
lexicographically smallest element as root so we will add one more condition while
union two sets.
 find_set(v) - returns the representative (also called leader) of the set that contains the
element v. This representative is an element of its corresponding set. It is selected in
each set by the data structure itself (and can change over time, namely after
union_sets calls). This representative can be used to check if two elements are part of
the same set or not. a and b are exactly in the same set, if find_set(a) == find_set(b).
Otherwise, they are in different sets.
 We iterate both string ‘s’ and ‘t’ and union all characters placed at the same index i.e.
 union(s[i],t[i]) where i goes from 0 -> s.length-1.
 And to make the lexicographically smallest string we just return the find_set value of
each character of ‘str’.
Algorithm:
 Declare an array parent of size 26 and initialize it with its index value.
 for( i : 0 -> s.length )
 union_set(s[i],t[i])
 Declare an empty string res =””
 for(i : 0 -> str.length )
 res += find_set( str[i] )
 return res
 Description of union_set(int a, int b)
 first find representation of each set
 a = find_set(a)
 b = find_set(b)
 If ( a != b )
 if( a < b )
 Parent[b] = a.
 else
 Parent[a] = b
 Description of find_set(int v)
 if( v == parent[v] ) return v.
 return parent[v] = find_set(v)

KESHAV MEMORIAL INSTITUTE OF TECHNOLOGY (AN AUTONOMOUS INSTITUTE)


COMPETITIVE PROGRAMMING UNIT-V III – II SEM (KR21 Regulations)

Java Program for Lexicographically Smallest Equivalent String:


LexSmallestEquivalentString.java
import java.util.*;
class LexSmallestEquivalentString
{

private class UnionFind


{
private int[] parent;

private UnionFind(int n)
{
parent = new int[n];
for(int i=0;i<n;i++)
{
parent[i] = i;
}
}
private int getAbsoluteParent(int i)
{
if(parent[i]==i)
{
// absolute parent
return i;
}
parent[i]=getAbsoluteParent(parent[i]);
return parent[i];
}

private void unify(int i, int j)


{
int absoluteParentI = getAbsoluteParent(i);
int absoluteParentJ = getAbsoluteParent(j);
if(absoluteParentI<absoluteParentJ)
{

parent[absoluteParentJ] = absoluteParentI ;
}
else
{

parent[absoluteParentI] = absoluteParentJ ;
}
}

}
public String smallestEquivalentString(String s1, String s2, String baseStr)

KESHAV MEMORIAL INSTITUTE OF TECHNOLOGY (AN AUTONOMOUS INSTITUTE)


COMPETITIVE PROGRAMMING UNIT-V III – II SEM (KR21 Regulations)

{
UnionFind uf = new UnionFind(26);

StringBuilder sb = new StringBuilder();

for(int i=0 ; i<s1.length() ; i++){

int charS1 = s1.charAt(i)-'a';


int charS2 = s2.charAt(i)-'a';

uf.unify(charS1, charS2 );
}

for(int i=0 ; i<baseStr.length() ; i++)


{
int smallestMappedChar = uf.getAbsoluteParent(baseStr.charAt(i)-'a');

sb.append((char)(smallestMappedChar+'a'));
}

return sb.toString();
}

public static void main(String args[])


{
Scanner sc=new Scanner(System.in);
String A=sc.next();
String B=sc.next();
String T=sc.next();
LexSmallestEquivalentString lses=new LexSmallestEquivalentString();
System.out.println(lses.smallestEquivalentString(A,B,T));
}
}

Sample input’s and output’s:


Example 1:
Input =attitude progress apriori
Output =aaogoog
Example 2:
Input =kmit ngit mgit
Output =ggit
Example 3:
Input =hello world hold
Output =hdld

KESHAV MEMORIAL INSTITUTE OF TECHNOLOGY (AN AUTONOMOUS INSTITUTE)


COMPETITIVE PROGRAMMING UNIT-V III – II SEM (KR21 Regulations)

2. Number of Distinct Islands:


Number of Distinct Islands states that given a n x m binary matrix. An island is a group
of 1‘s (representing land) connected 4-directionally (horizontal or vertical).

An island is considered to be the same as another if and only if one island can be translated
(and not rotated or reflected) to equal the other.

Example-1:
Input: [[1,1,0,0,0],[1,1,0,0,0],[0,0,0,1,1],[0,0,0,1,1]]
Output: 1
Explanation:

 Check the above diagram for a better understanding.


 Note that we cannot rotate or reflect the orientation of the island.
 In the above figure, both the islands are identical, hence the number of distinct islands is
1.
Example-2:

Input: [[1,1,0,1,1],[1,0,0,0,0],[0,0,0,0,1],[1,1,0,1,1]]
Output: 3
Explanation:

KESHAV MEMORIAL INSTITUTE OF TECHNOLOGY (AN AUTONOMOUS INSTITUTE)


COMPETITIVE PROGRAMMING UNIT-V III – II SEM (KR21 Regulations)

 Check the above diagram for a better understanding.


 Note that islands on the top right corner and bottom left corner are identical, while
islands on the top left corner and bottom right corner are different.
 Hence, the total number of distinct islands is 3.

Java Program for Number of Distinct Islands: DistinctIslandsUF.java


import java.util.*;
public class DistinctIslandsUF
{
private int size[];
private int p[];
private int N, M;

public int find(int i)


{
while (p[i]>=0)
i=p[i];
return i;
}
public void union(int i, int j)
{
int ri = find(i);
int rj = find(j);

if (ri == rj)
return;

if (size[ri] < size[rj])


{
size[rj] += size[ri];
p[ri] = rj;
}
else
{
size[ri] += size[rj];
p[rj] = ri;
}
}
private boolean inside(int x, int y)
{

KESHAV MEMORIAL INSTITUTE OF TECHNOLOGY (AN AUTONOMOUS INSTITUTE)


COMPETITIVE PROGRAMMING UNIT-V III – II SEM (KR21 Regulations)

return (x >= 0 && y >= 0 && x < N && y < M);


}
public int numIslands(int grid[][])
{
if (grid == null || grid.length ==0) return 0;
N = grid.length;
M = grid[0].length;
size = new int[N*M];
p = new int[N*M];
List<int[]> ones = new ArrayList<>();

for (int i = 0; i < N*M; i++)


{
p[i] = -1;
size[i] = 1;
}

for (int i = 0; i < N; i++)


{
for (int j = 0; j < M; j++)
if (grid[i][j] != 0)
{
int[] pos = new int[2];
pos[0] = i;
pos[1]= j;
ones.add(pos);
int tmp = i*M + j;
if (inside(i-1, j) && grid[i-1][j] != 0) union(tmp, tmp - M);
if (inside(i, j-1) && grid[i][j-1] != 0) union(tmp, tmp - 1);
if (inside(i+1, j) && grid[i+1][j] != 0) union(tmp, tmp + M);
if (inside(i, j+1) && grid[i][j+1] != 0) union(tmp, tmp + 1);
}
}

HashMap<Integer, Queue<int[]>> map = new HashMap<>();


for (int[] pos : ones)
{
int x = pos[0], y = pos[1], p = find(x * M + y);
Queue<int[]> queue = map.getOrDefault(p, new LinkedList<int[]>());
queue.add(pos);

KESHAV MEMORIAL INSTITUTE OF TECHNOLOGY (AN AUTONOMOUS INSTITUTE)


COMPETITIVE PROGRAMMING UNIT-V III – II SEM (KR21 Regulations)

map.put(p, queue);
}

HashSet<String> strs = new HashSet<>();


for (int k : map.keySet())
{
Queue<int[]> queue = map.get(k);
int[] dd = queue.peek();
int dx = dd[0], dy = dd[1];
StringBuilder sb = new StringBuilder();
while (!queue.isEmpty())
{
int[] cur = queue.remove();
sb.append(cur[0] - dx);
sb.append(",");
sb.append(cur[1] - dy);
sb.append(";");
}
strs.add(sb.toString());
}

return strs.size();
}
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
int m=sc.nextInt();
int n=sc.nextInt();
int grid[][]=new int[m][n];
for(int i=0;i<m;i++)
for(int j=0;j<n;j++)
grid[i][j]=sc.nextInt();
System.out.println(new DistinctIslandsUF().numIslands(grid));
}
}

KESHAV MEMORIAL INSTITUTE OF TECHNOLOGY (AN AUTONOMOUS INSTITUTE)


COMPETITIVE PROGRAMMING UNIT-V III – II SEM (KR21 Regulations)

Sample input’s and output’s:

Example: 1
Input =4 5
11000
11000
00011
00011
Output =1

Example:2
Input =5 5
11011
10001
00000
10001
11011
Output =4

KESHAV MEMORIAL INSTITUTE OF TECHNOLOGY (AN AUTONOMOUS INSTITUTE)


COMPETITIVE PROGRAMMING UNIT-V III – II SEM (KR21 Regulations)

3. Number of Connected Components in an Undirected Graph:


Given an undirected graph G with vertices numbered in the range [0, N] and an array
Edges[][] consisting of M edges, the task is to find the total number of connected
components in the graph using Disjoint Set Union algorithm.

Examples:
Input: N = 5, Edges[][] = {{1, 0}, {2, 3}, {3, 4}}
Output: 2
Explanation: There are only 2 connected components as shown below:

Input: N = 8, Edges[][] = {{1, 0}, {0, 2}, {3, 5}, {3, 4}, {6, 7}}
Output: 3
Explanation: There are only 3 connected components as shown below:

Approach:

The problem can be solved using Disjoint Set Union algorithm. Follow the steps below to
solve the problem:
 In DSU algorithm, there are two main functions, i.e. connect() and root() function.
 connect(): Connects an edge.
 root(): Recursively determine the topmost parent of a given edge.
 For each edge {a, b}, check if a is connected to b or not. If found to be false, connect
them by appending their top parents.
 After completing the above step for every edge, print the total number of the distinct top-
most parents for each vertex.

KESHAV MEMORIAL INSTITUTE OF TECHNOLOGY (AN AUTONOMOUS INSTITUTE)


COMPETITIVE PROGRAMMING UNIT-V III – II SEM (KR21 Regulations)

Java Program for Number of Connected Components in an Undirected Graph:


ConnectedComponents.java
import java.util.*;

class ConnectedComponents
{
int[] parent;
int[] size;
public int countComponents(int n, int[][] edges)
{
parent = new int[n];
size = new int[n];
for (int i = 0; i < n; i++)
{
parent[i] = -1;
size[i] = 1;
}
int components = n;
for (int[] e : edges)
{
int p1 = find(e[0]);
int p2 = find(e[1]);
if (p1 != p2)
{
if (size[p1] < size[p2])
{ // Merge small size to large size
size[p2] += size[p1];
parent[p1] = p2;
}
else
{
size[p1] += size[p2];
parent[p2] = p1;
}
components--;
}
}
return components;
}
private int find(int i)
{
while(parent[i]>=0)
i = parent[i];

KESHAV MEMORIAL INSTITUTE OF TECHNOLOGY (AN AUTONOMOUS INSTITUTE)


COMPETITIVE PROGRAMMING UNIT-V III – II SEM (KR21 Regulations)

return i;
}

public static void main(String args[])


{
Scanner sc= new Scanner(System.in);
int n=sc.nextInt();
int e=sc.nextInt();
int edges[][]=new int[e][2];
for(int i=0;i<e;i++)
for(int j=0;j<2;j++)
edges[i][j]=sc.nextInt();
System.out.println(new ConnectedComponents().countComponents(n,edges));
}
}
Case =1
Input =5 6
01
02
23
12
14
24
Output =1
Case =2
Input =5 4
01
02
12
34
Output =2
Case =3
Input =6 3
01
23
45
Output =3

KESHAV MEMORIAL INSTITUTE OF TECHNOLOGY (AN AUTONOMOUS INSTITUTE)

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy