标签:
问题描述:
import java.util.Scanner; import java.util.Arrays; import java.math.BigInteger; public class Main{ static int n,m; static int[] isRoot=new int[2000]; static int[] pre=new int[2000]; static Scanner in=new Scanner(System.in); public static void main(String args[]){ int count; while(in.hasNextInt()){ n=in.nextInt(); if(n==0) break; m=in.nextInt(); count=0; int x,y; for(int i=1;i<=n;i++){ isRoot[i]=1; pre[i]=i; } for(int i=0;i<m;i++){ x=in.nextInt(); y=in.nextInt(); mix(x,y); } for(int i=1;i<=n;i++) if(find(i)==i) count++; System.out.println(count-1); } } public static int find(int x){ int r=x; while(r!=pre[r]){ r=pre[r]; } int i=x,j; while(i!=r){ j=pre[i]; pre[i]=r; i=j; } return r; } public static void mix(int x,int y){ int fx=find(x); int fy=find(y); if(fx!=fy){ pre[fy]=fx; } } }
标签:
原文地址:http://www.cnblogs.com/burning-flame/p/4930982.html