并查集的简单应用:
代码:
1 #include<cstdio> 2 #define maxn 100005 3 using namespace std; 4 int f[maxn]; 5 int find(int x){return x==f[x]?x:f[x]=find(f[x]);} 6 int main() 7 { 8 int x,y; 9 while(scanf("%d",&x)!=EOF) 10 { 11 for(int i=0;i<maxn;i++)f[i]=i; 12 int cnt=0; 13 while(x!=-1) 14 { 15 scanf("%d",&y); 16 x=find(x),y=find(y); 17 if(x==y)cnt++; 18 else f[x]=y; 19 scanf("%d",&x); 20 } 21 printf("%d ",cnt); 22 } 23 return 0; 24 }