简单的并查集。
#include<cstdio>
#define mx 100010
int fa[mx];
int find(int x)
{
while(fa[x]!=x) x=fa[x];
return x;
}
int main()
{
int i,x,y,cnt;
while(scanf("%d",&x)!=EOF)
{
for(i=0;i<mx;i++) fa[i]=i;
cnt=0;
while(x!=-1)
{
scanf("%d",&y);
x=find(x);y=find(y);
if(x==y) cnt++;
else fa[x]=y;
scanf("%d",&x);
}
printf("%d\n",cnt);
}
return 0;
}