4 2 1 3 4 3 3 3 1 2 1 3 2 3 5 2 1 2 3 5 999 0 0
1 0 2 998 这道题是典型的并查集题,刚学会并查集,做了这道简单的题代码:#include<stdio.h> #include<string.h> int a[1001] ; int find(int x) { if(a[x] == x) return x ; return find(a[x]); } void merge(int x,int y) { int m1 = find(x) ; int m2 = find(y) ; if(m1 != m2) a[m2] = m1; } int main() { int N = 0 , M = 0 ; while(~scanf("%d",&N)) { M = 0 ; if( N == 0 ) break ; int i = 0 ,j = 0 ; memset(a , 0 , sizeof(a)); for(i = 1 ;i <= N ; i++) a[i] = i ; scanf("%d", &M); int x = 0, y = 0 ; for(i = 0 ; i < M ; i++) { scanf("%d%d",&x,&y); merge(x , y) ; } int count = 0 ; for(i = 1 ;i <= N ; i++) if(a[i] == i) count++; printf("%d\n",count-1); } return 0 ; }
原文:http://blog.csdn.net/bluedream1219/article/details/37882459