LA 3644

来源:互联网 发布:知乎每日精选 编辑:程序博客网 时间:2024/04/28 18:27

题目:http://acm.hust.edu.cn:8080/judge/problem/viewProblem.action?id=12648


并查集得到运用,检查X,Y是否在同一个集合中,如果是++cnt,反之将Y存入集合。

#include<cstdio>using namespace std;const int maxn = 100000+10;int f[maxn];int find(int x){    if(f[x]!=x) return f[x]=find(f[x]);    return x;}int main(){    int x,y;    while( scanf("%d",&x)!=EOF ){          for(int i=0;i<maxn;i++) f[i]=i;          int ans=0;          while(x!=-1){               scanf("%d",&y);               int fx=find(x); int fy=find(y);               if(fx==fy)  ans++;               else      f[fx]=fy;               scanf("%d",&x);          }          printf("%d\n",ans);    }    return 0;}


原创粉丝点击