指南 第三章 例题5 UVALive 3644 X-Plosives(并查集)

来源:互联网 发布:杭州锐智软件 编辑:程序博客网 时间:2024/06/11 04:03

题目链接:http://7xjob4.com1.z0.glb.clouddn.com/eab170e979d9683005d958b058d6ce76

思路:就是加入后成环的元素不可以被加入。

下面是AC代码:

#include<cstdio>const int maxn=100000+10;int pre[maxn];int findset(int x){    if(x==pre[x])    {        return x;    }    else    {        return pre[x]=findset(pre[x]);    }}int main(){    int x,y;    while(scanf("%d",&x)==1)    {        for(int i=0;i<=maxn;i++)        {            pre[i]=i;        }        int refusales=0;        while(x!=-1)        {            scanf("%d",&y);            x=findset(x);            y=findset(y);            if(x==y)            {                ++refusales;            }            else            {                pre[x]=y;            }            scanf("%d",&x);        }        printf("%d\n",refusales);    }    return 0;}
0 0
原创粉丝点击