1. 程式人生 > >大家快來A水題 2805

大家快來A水題 2805

大家快來A水題

Problem Description
海上有N(1<= N <=2000)個島,編號從1到N,同一部落的島嶼之間有直接或間接的路相連,不同部落之間無路可通。現在給出M(1<= M <= N*(N-1)/2)條路。問這片海域上共有多少部落。
Input
多組輸入。每組第一行輸入N,M。接下來M行每行,每行兩個整數u,v代表島u與v之間有一條路。
Output
每組資料輸出一個整數,代表部落數。
Sample Input
3 1
1 2
3 2
1 2
1 3
Sample Output
2
1

#include <stdio.h>
#include <stdlib.h> int f[11000]; int find(int x) { if(x!=f[x]) { f[x]=find(f[x]); } return f[x]; } void join(int x,int y) { x=find(x); y=find(y); if(x!=y) { f[y]=x; } } int main() { int m,u,v,i,n,c; while(scanf("%d%d",&n,&m)!=EOF
) { for(i=1;i<=n;i++) f[i]=i; for(i=0;i<m;i++) { scanf("%d%d",&u,&v); join(u,v); } c=0; for(i=1;i<=n;i++) { if(f[i]==i) c++; } printf("%d\n",c); } return
0; }