hdu 2120 Ice_cream's world I
判断环的个数
#include <stdio.h>
#include <string.h>
#define MAXN 1003
int father[MAXN];
int find(int x)
{
int i,t;
for(i=x; father[i]>=0; i=father[i]) ;
while(x!=i)
{
t=father[x];
father[x]=i;
x=t;
}
return i;
}
bool merge(int x,int y)
{
int fx=find(x),fy=find(y);
if(fx==fy) return false;
if(father[fx]>father[fy])
{
father[fy]+=father[fx];
father[fx]=fy;
}
else
{
father[fx]+=father[fy];
father[fy]=fx;
}
return true;
}
int main()
{
int N,M,i,j;
while(scanf("%d %d",&N,&M)!=EOF)
{
memset(father,-1,sizeof(*father)*(N+1));
int cnt=0;
while(M--)
{
scanf("%d %d",&i,&j);
if(!merge(i,j)) cnt++;
}
printf("%d\n",cnt);
}
return 0;
}
浙公网安备 33010602011771号