http://acm.hdu.edu.cn/showproblem.php?pid=1232
题目 | 题意 |
给出城市个数,及已联通城市,求连通图需要再建几条路 | 并查集 |
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int m,n,i,a,b,t;
Scanner oo=new Scanner(System.in);
while(oo.hasNext()){
n=oo.nextInt();
if(n==0){break;}
m=oo.nextInt();
int pre[]=new int[n+1];
for(i=1;i<=n;i++){
pre[i]=i;
}
t=n-1;
for(i=0;i<m;i++){
a=oo.nextInt();
b=oo.nextInt();
while(a!=pre[a]){
a=pre[a];
}
while(b!=pre[b]){
b=pre[b];
}
if(a!=b){
pre[a]=pre[b];
t--;
}
}
System.out.println(t);
}
}
}