解法1:畅通工程,自己写的没通过,暂时没找到bug
import java.util.*;
public class Main2 {
public static void main(String args[]){
Scanner in=new Scanner(System.in);
while(in.hasNext()){
int n=in.nextInt();
if(n==0){
break;
}
int m=in.nextInt();
int father[]=new int[n+1];
Make(father);
for(int i=0;i<m;i++){
int x=in.nextInt();
int y=in.nextInt();
Combine(x,y,father);
}
int cnt=0;
for(int i=1;i<=father.length-1;i++){
if(i==Find(i,father)){
cnt++;
}
}
System.out.println(cnt-1);
}
}
public static void Make(int father[]){
for(int i=1;i<=father.length-1;i++){
father[i]=i;
}
}
public static int Find(int x,int father[]){
while(x!=father[x]){
x=father[x];
}
return x;
}
public static void Combine(int x,int y,int father[]){
int x_father=Find(x,father);
int y_father=Find(y,father);
if(x_father!=y_father){
if(y>x){
father[y]=x;
}else{
father[x]=y;
}
}
}
}
做如下更改可以通过。
解法2:网上的解法,思想和我的一样,AC通过了。
import java.util.Scanner;
public class Main{
static int pre[];
static int find(int x){
if(pre[x] == x) return x;
return pre[x] = find(pre[x]);
}
static void link(int x,int y){
int xx = find(x);
int yy = find(y);
if(xx>yy) pre[xx] = yy;
else pre[yy] = xx;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while(sc.hasNext()){
int n = sc.nextInt();
if(n==0) break;
int m = sc.nextInt();
pre = new int[n+1];
for (int i = 0; i < pre.length; i++) {
pre[i] = i;
}
int root = 1;
for (int i = 0; i < m; i++) {
int a = sc.nextInt();
int b = sc.nextInt();
link(a,b);
}
int ans = 0;
for (int i = 1; i < pre.length; i++) {
if(i!=root && find(i) != root){
link(i,root);
ans++;
}
}
System.out.println(ans);
}
}
}
写法3:AC
import java.util.*;
public class Main {
public static void main(String args[]) {
Scanner in=new Scanner(System.in);
while(true) {
int N=in.nextInt();
if(N==0)
break;
int M=in.nextInt();
int father[]=new int[N+1];
for(int i=1;i<=N;i++)
father[i]=i;
for(int i=0;i<M;i++) {
int starttemp=in.nextInt();
int endtemp=in.nextInt();
int finds=Find(starttemp,father);
int finde=Find(endtemp,father);
int start=Math.min(finds, finde);
int end=Math.max(finds,finde);
father[end]=start;
}
int cnt=-1;
for(int i=1;i<=N;i++)
if(father[i]==i)
cnt++;
System.out.println(cnt);
}
}
public static int Find(int pos,int father[]) {
while(father[pos]!=pos)
pos=father[pos];
return pos;
}
}