1、 hdu1232
2、链接:http://acm.hdu.edu.cn/showproblem.php?pid=1232
3、总结:简单并查集
#include<iostream> #include<cstring> #include<cmath> #include<queue> #include<algorithm> #include<cstdio> using namespace std; #define LL long long #define INF 0x3f3f3f3f const int N=1010; int father[N]; /* //未优化的查找 int findn(int n) { while(father[n]!=n){ n=father[n]; } return n; } */ int findn(int n) { int x=n; while(father[x]!=x){ x=father[x]; } int i=n,j; while(father[i]!=x) //优化 { j=father[i]; father[i]=x; i=j; } return x; } int main() { int n,m; while(scanf("%d",&n)!=EOF&&n) { //初始化 for(int i=1;i<=n;i++) father[i]=i; scanf("%d",&m); int x,y; for(int i=0;i<m;i++) { scanf("%d%d",&x,&y); //合并 int tempx=findn(x); int tempy=findn(y); if(tempx!=tempy)father[tempx]=tempy; } //找出连通分量的个数,减一 int num=0; for(int i=1;i<=n;i++) { if(father[i]==i)num++; } printf("%d ",num-1); } return 0; }