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<stdio.h> #include<memory> #include<iostream> #include<algorithm> #include<string.h> #include<math.h> using namespace std; int father[51000],rank[51000]; int getfather(int a) { int res,p,tep; if(a==father[a]) res=a; else { p=a; while(p!=father[p]) p=father[p]; while(a!=p) { tep=a;father[tep]=p;a=father[a]; } res=p; } return res; } int main() { int N,M,i,x,y,x1,y1,num,count=0; while(1) { count++; scanf("%d%d",&N,&M); if(N==0&&M==0) break; memset(father,0,sizeof(father)); memset(rank,0,sizeof(rank)); for(i=1;i<=N;i++) { father[i]=i; rank[i]=1; } num=N; for(i=0;i<M;i++) { scanf("%d%d",&x,&y); x1=getfather(x);y1=getfather(y); if(x1!=y1) { if(rank[x1]>rank[y1]) { rank[x1]+=rank[y1]; father[y1]=father[x1]; } else { rank[y1]+=rank[x1]; father[x1]=father[y1]; } num--; } } printf("Case %d: %d\n",count,num); } return 0; } Followed by: Post your reply here: |
All Rights Reserved 2003-2013 Ying Fuchen,Xu Pengcheng,Xie Di
Any problem, Please Contact Administrator