http://poj.org/problem?id=2524
此题求连通分量的数目,之前我也想这么做,可是怎么找呢。。。。好麻烦,后经提醒合并一次减去一个啊,好简单于是就这样水过。
还有个地方调了好久,n重复定义,除了主函数地址就变了,还以为编译器坏了- -。太大意了。
睡觉-,-tomorrow will be a good day.
cqlf | 2524 | Accepted | 888K | 297MS | G++ | 969B | 2012-03-21 01:29:35 |
#include<iostream> #include<cstdio> #include<cstring> using namespace std; int n,m,num; int pre[50005]; void UFset() { for(int i=0;i<n;i++) pre[i]=-1; } int Find(int x) { int ss; for(ss=x;pre[ss]>=0;ss=pre[ss]);//find root // { printf("%d\n",pre[ss]) //system("pause"); // } while(ss!=x) { int tmp=pre[x]; pre[x]=ss; x=tmp; } return ss; } void Union(int R1,int R2) { int r1=Find(R1); int r2=Find(R2); int tmp=pre[r1]+pre[r2];//tmp is negative if(r1==r2) return; if(pre[r1]>pre[r2]) { pre[r1]=r2; pre[r2]=tmp; num--; } else { pre[r2]=r1; pre[r1]=tmp; num--; } } int main() { int i,Case=1; int a,b;//relation students while(scanf("%d%d",&n,&m)) { if(n==0&&m==0) break; num=n; UFset(); // for(i=0;i<10;i++) // printf("%d\n",pre[i]); for(i=0;i<m;i++) { scanf("%d%d",&a,&b); Union(a,b); } printf("Case %d: %d\n",Case++,num); } return 0; }