-
Notifications
You must be signed in to change notification settings - Fork 20
/
components-in-a-graph.java
57 lines (52 loc) · 1.69 KB
/
components-in-a-graph.java
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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
// https://www.hackerrank.com/challenges/components-in-graph
import java.io.*;
import java.util.*;
public class Solution {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
UF uf = new UF();
uf.init(2*n);
for (int i = 1; i <=n; i++) {
int g = sc.nextInt();
int b = sc.nextInt();
uf.union(g, b);
}
int maxSize = Integer.MIN_VALUE, minSize = Integer.MAX_VALUE;
for (int i = 1; i <= 2*n; i++) {
int p = uf.find(i);
int s = uf.size[p];
if (s > 1) {
if (minSize > s) minSize = s;
if (maxSize < s) maxSize = s;
}
}
System.out.println(minSize + " " + maxSize);
}
static class UF {
static final int MAXN = 30001;
int parent[] = new int[MAXN];
int size[] = new int[MAXN];
public void init(int n) {
for (int i = 1; i <= n; i++) {
parent[i] = i;
size[i] = 1;
}
}
public void union(int u, int v) {
int i = find(u);
int j = find(v);
// System.out.println("u= " + u + ", v= " + v + ", i= " + i + ", j= " + j);
if (i == j) return;
parent[i] = j;
size[j] += size[i];
// System.out.println("size[" + j + "]= " + size[j]);
// if (size[j] > maxSize) maxSize = size[j];
// if (size[j] < minSize) minSize = size[j];
}
public int find(int u) {
if (parent[u] == u) return u;
else return parent[u] = find(parent[u]);
}
}
}