Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added code for components in a graph problem #463

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 45 additions & 0 deletions componentsInAgraph.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import java.io.*;
import java.util.*;

public class Solution {

public static void main(String[] args) {
/* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int[] parent = new int[2 * n + 1];
int[] count = new int[2 * n + 1];
for (int i = 1; i <= 2 * n; i++) {
count[i] = 1;
parent[i] = i;
}
for (int i = 0; i < n; i++) {
int g = scanner.nextInt();
int b = scanner.nextInt();
int root_g = g;
int root_b = b;
while (parent[root_g] != root_g) root_g = parent[root_g];
while (parent[root_b] != root_b) root_b = parent[root_b];
if (root_b == root_g) continue;
if (count[root_b] < count[root_g]) {
parent[root_b] = root_g;
count[root_g] += count[root_b];
} else {
parent[root_g] = root_b;
count[root_b] += count[root_g];
}
//System.out.println(g + "::" + b);
//System.out.println(parent[g] + "->" + parent[b]);
}
int min = 2 * n + 1;
int max = 2;
for (int i = 1; i <= 2 * n; i++) {
if (parent[i] != i) continue;
if (count[i] == 1) continue;
min = Math.min(min, count[i]);
max = Math.max(max, count[i]);
//System.out.println(i + ":" + count[i]);
}
System.out.println(min + " " + max);
}
}