水题啊,水题,并查集。。。。
package poj;
import java.util.Scanner;
/**
* @description POJ 2524 Ubiquitous Religions
* @technique 并查集
* @date 20120814
* @time 13:14
* @version 1.0
* @author Alex
* @result AC
*
*/
public class Poj2524_20120814_0 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n, m,x,y,i,cas = 0;
int [] rank;
int [] father;
while(true){
n = in.nextInt();
m = in.nextInt();
if((m|n) == 0){
break;
}
father = new int[n];
rank = new int[n];
makeSet(father);
for(i = 0; i < m; ++i){
x = in.nextInt();
y = in.nextInt();
union(father, rank, x-1,y-1);
}
System.out.println("Case " + (++cas) + ": " + count(father));
}
}
private static int count(int [] father){
int count = 0;
for(int i = 0; i < father.length; ++i){
if(father[i] == i){
++count;
}
}
return count;
}
private static void makeSet(int [] father){
for(int i = 0; i < father.length; ++i){
father[i] = i;
}
}
private static int findx(int [] father,int x){
if(father[x] != x){
father[x] = findx(father, father[x]);
}
return father[x];
}
private static void union(int [] father, int [] rank, int x, int y){
int fx = findx(father,x);
int fy = findx(father,y);
if(rank[fx] == rank[fy]){
father[fy] = fx;
rank[fx] += 1;
}else{
if(rank[fx]>rank[fy]){
father[fy] = fx;
}else{
father[fx] = fy;
}
}
}
}