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];
}
}
}
并查集
最新推荐文章于 2023-05-12 16:29:23 发布