题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1232
package D0802;
//简单的单纯并查集问题
import java.io.*;
public class HDU1232 {
static int[] set = new int[1008];
static int[] height = new int[1008];
public static void main(String[] args) throws IOException {
//用scanner读入一直错,不知道为什么
StreamTokenizer st = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
int n, m;
while (st.nextToken()!=StreamTokenizer.TT_EOF) {
n = (int)st.nval;
st.nextToken();
m = (int)st.nval;
if (n == 0)
break;
init(n);// 初始化集合
while (m-- > 0) {
st.nextToken();
int a = (int)st.nval;
st.nextToken();
int b = (int)st.nval;
int x = find(a);
int y = find(b);
// 合并ab到一个集合
if (x != y)
merge(x, y);
}
// 查找有多少个不同的集合
int k = 0;
for (int i = 1; i <= n; i++) {
if (set[i] == i) {
k++;
}
}
System.out.println(k - 1);
}
}
// 合并集合
public static void merge(int a, int b) {
if (height[a] < height[b])
set[a] = b;
else if (height[a] > height[b])
set[b] = a;
else {
set[b] = a;
height[a]++;
}
}
// 查找x属于哪个集合
public static int find(int x) {
while (set[x] != x)
x = set[x];
return x;
}
// 初始化数组
public static void init(int n) {
for (int i = 1; i < n + 1; i++) {
set[i] = i;
height[i] = 1;
}
}
}