/** * @link http://acm.hdu.edu.cn/showproblem.php?pid=1232 * @author Sycamore * @date Aug, 18 */import java.util.*; class Main{ static int []parent=new int[1000]; static int find(int x) { return parent[x]=x==parent[x]?x:find(parent[x]); } static void Union(int x,int y) { parent[find(x)]=find(y); } public static void main(String args[]){ Scanner scanner=new Scanner(System.in); while(scanner.hasNext()) { int n=scanner.nextInt(); if(n==0)break; int m=scanner.nextInt(); for(int i=1;i<=n;i++)parent[i]=i; for(int i=0;i<m;i++) { int a=scanner.nextInt(),b=scanner.nextInt(); Union(a,b); } int cnt=0; for(int i=1;i<=n;i++) if(parent[i]==i) ++cnt; System.out.println(cnt-1); } scanner.close(); }}
时间: 2024-12-06 10:12:18