-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathComponents in a graph.java
More file actions
41 lines (39 loc) · 1.37 KB
/
Components in a graph.java
File metadata and controls
41 lines (39 loc) · 1.37 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
import java.io.*;
import java.util.*;
public class Solution {
public static void main(String[] args) {
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];
}
}
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(min + " " + max);
}
}