POJ 1611 The Suspects

来源:互联网 发布:日本留学生中国知乎 编辑:程序博客网 时间:2024/06/05 21:03

并查集问题。

也可以说是模版题。其实不用开c数组也行的。

既然是模版题,我就直接套上道并查集的模版。

就是在合并的时候把优先判 0 ;

POJ AC代码:

#include<cstdio>#include<cstring>#include<algorithm>using namespace std;int a[30001],c[30001];void intt(int n){    for(int i=0;i<n;i++)    a[i]=i,c[i]=1;}int findset(int x){    if(a[x]!=x)    a[x]=findset(a[x]);    return a[x];}void unionset(int x,int y){    x=findset(x),y=findset(y);    if(x==y)return ;    if(x==0)    {        a[y]=x,c[x]+=c[y];        return ;    }    if(y==0)    {        a[x]=y,c[y]+=c[x];        return ;    }    if(c[x]>=c[y])    {        a[y]=x,c[x]+=c[y];    }    else    {        a[x]=y,c[y]+=c[x];    }}int main(){    int n,m,i,j,t,x,y;    while(scanf("%d%d",&n,&m),n!=0||m!=0)    {        intt(n);        while(m--)        {            scanf("%d%d",&t,&x);            t--;            while(t--)            {                scanf("%d",&y);                unionset(x,y);            }        }        int ans=0;        for(i=0;i<n;i++)        {            a[i]=findset(i);            if(a[i]==0)ans++;        }        printf("%d\n",ans);    }}


原创粉丝点击