一道简单的并查集。。题意其实就是判断是否有环。。
// File Name: 1160.cpp // Author: zlbing // Created Time: 2013/3/8 21:26:11 #include<iostream> #include<string> #include<algorithm> #include<cstdlib> #include<cstdio> #include<set> #include<map> #include<vector> #include<cstring> #include<stack> #include<cmath> #include<queue> using namespace std; #define CL(x,v); memset(x,v,sizeof(x)); #define INF 0x3f3f3f3f #define LL long long #define REP(i,n) for(int i=0;i<n;i++) #define REP1(i,n) for(int i=1;i<n+1;i++) const int MAXN=100050; int f[MAXN]; int find(int x){ return x==f[x]?x:f[x]=find(f[x]); } int main(){ int a,b; while(~scanf("%d",&a)){ int ans=0; REP1(i,MAXN-5)f[i]=i; while(a!=-1){ scanf("%d",&b); int fx=find(a); int fy=find(b); if(fx==fy)ans++; else f[fx]=fy; scanf("%d",&a); } printf("%d\n",ans); } return 0; }