Online Judge | Problem Set | Authors | Online Contests | User | ||||||
---|---|---|---|---|---|---|---|---|---|---|
Web Board Home Page F.A.Qs Statistical Charts | Current Contest Past Contests Scheduled Contests Award Contest |
并查集,压缩路径和不压缩路径两种方法,附代码#include<cstdio> #include<cstring> int n,m,p[50005],ans; void ini() { int i; for(i=1;i<=n;i++) p[i]=i; } int find(int x) //压缩路径 { if(p[x]!=x)return p[x]=find(p[x]); return p[x]; } /*int find(int x) //不压缩路径 { while(p[x]!=x)x=p[x]; return x; }*/ void combine(int x,int y) { x=find(x); y=find(y); if(x!=y) { ans--; p[y]=x; } } int main() { int i,a,b,k=1; while(scanf("%d%d",&n,&m)!=EOF) { if(m==0&&n==0)break; ini(); ans=n; for(i=1;i<=m;i++) { scanf("%d%d",&a,&b); combine(a,b); } printf("Case %d: %d\n",k++,ans); } return 0; } Followed by: Post your reply here: |
All Rights Reserved 2003-2013 Ying Fuchen,Xu Pengcheng,Xie Di
Any problem, Please Contact Administrator