树思想,使用并查集,类似Kruskal算法
代码:
package Test1;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StreamTokenizer;
public class Test36_1012 {
/**
* by qr jobdu 1012 2014-8-19
*
* @throws IOException
*/
public static void main(String[] args) throws IOException {
StreamTokenizer st = new StreamTokenizer(new BufferedReader(
new InputStreamReader(System.in)));
int n, m;
while (true) {
st.nextToken();
n = (int) st.nval;
if (n == 0)
break;
st.nextToken();
m = (int) st.nval;
int arr[][] = new int[n + 1][n + 1];
UnionFindSet ufs=new UnionFindSet(n+1);
int n1, n2, num = 0;
for (int i = 0; i < m; i++) {
st.nextToken();
n1 = (int) st.nval;
st.nextToken();
n2 = (int) st.nval;
if (arr[n1][n2] == 0 ) {
arr[n1][n2] = 1;
arr[n2][n1] = 1;
if(ufs.find(n1)!=ufs.find(n2)){
ufs.union(n1,n2);
num++;
}
}
}
if (num >= n)
System.out.println(0);
else
System.out.println(n - 1 - num);
}
}
}
class UnionFindSet {
int set[];
int size[];
UnionFindSet() {
}
UnionFindSet(int n) {
set = new int[n];
size = new int[n];
for (int i = 0; i < n; i++) {
set[i] = i;
size[i] = 1;
}
}
int find(int i){
while(i!=set[i]){
i=set[i];
}
return i;
}
void union(int i,int j){
int p=find(i);
int q=find(j);
if(size[p]<size[q]){
set[p]=q;
size[q]+=size[p]; //勿忘修改size
}else{
set[q]=p;
size[p]+=size[q];
}
}
}