-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuf.java
More file actions
62 lines (54 loc) · 1.15 KB
/
Copy pathuf.java
File metadata and controls
62 lines (54 loc) · 1.15 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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
/*************************************************************************
> File Name: uf.java
> Author: Weiang
> Mail: weiang@mail.ustc.edu.cn
> Created Time: 2013年09月29日 星期日 11时41分04秒
> Describition:
************************************************************************/
public class UF
{
private int[] id;
private int count;
public UF(int n)
{
// Initialize component id array.
count = n;
id = new int[n];
for (int i = 0; i < n; i ++)
id[i] = i;
}
public int count()
{
return count;
}
public boolean connected(int p, int q)
{
return find(p) == find(q);
}
public int find(int p)
{
return id[p];
}
public void union(int p, int q)
{
int pid = id[p];
int qid = id[q];
if (pid == qid) return;
count --;
for (int i = 0; i != id.length; i ++)
if (id[i] == qid) id[i] = pid;
}
public static void main(String[] args)
{
int n = StdIn.readInt();
UF uf = new UF(n);
while (!StdIn.isEmpty()) {
int p = StdIn.readInt();
int q = StdIn.readInt();
if (uf.connected(p, q)) continue;
uf.union(p, q);
StdOut.println(p + " " + q);
}
StdOut.println(uf.count() + " components");
}
}