您的位置:首页 > 其它

并查集

2016-03-06 20:39 225 查看
import java.util.Scanner;

public class T1012 {
static int[] Tree = new int[1001];
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n, m,count;
while ((n = sc.nextInt()) != 0) {
count =0 ;
m = sc.nextInt();
for (int i = 1; i < n+1; i++) {
Tree[i] = -1;
}
for (int i = 0; i < m; i++) {
int a = sc.nextInt();
int b = sc.nextInt();
a = findRoot(a);
b = findRoot(b);
if(a!=b)Tree[a] = b;
}
for(int i = 1 ; i < n+1 ; i++){
if(Tree[i]==-1)count++;
}
System.out.println(count-1);
}
}

static int findRoot(int x) {
if (Tree[x] == -1)return x;
else {
Tree[x] = findRoot(Tree[x]);
return Tree[x];
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: