poj 2492 并查集 A Bug's Life

来源:互联网 发布:印度导航系统 知乎 编辑:程序博客网 时间:2024/04/29 08:17

这道题可以用disset数组来装每个虫的对象,并把对象合并到一起,
然后看看如果偶有一组的数根相等,那么就是有问题了

#include<iostream>
using namespace std;
#define max 2010
int pa[max];
int rank[max];
int disset[max];
void make_set(int x)
{
 pa[x]=x;
 rank[x]=0;
 disset[x]=-1;
 return ;
}
int find_set(int x)
{
 if(x!=pa[x])
 pa[x]=find_set(pa[x]);
 return pa[x];
}
void union_set(int x,int y)
{
 x=find_set(x);
 y=find_set(y);
 if(x==y) return ;
 if(rank[x]>rank[y])
 pa[y]=x;
 else
 {
  pa[x]=y;
  if(rank[x]==rank[y])
  rank[y]++;
 }
 return ;
}
int main()
{
 int p=1;
 int cases;
 bool flag;
 int x,y;
 cin>>cases;
 while(cases--)
 {
  int bug;
  long pair;
  scanf("%d%ld",&bug,&pair);
  for(int i=0;i<=bug;i++)//初始化赋值让我给整错了
  make_set(i);
  flag=false;
  while(pair--)
  {
   scanf("%d%d",&x,&y);
   if(flag)
   continue;
   
   if(find_set(x)==find_set(y))
   flag=true;
   else
   {
    if(disset[x]!=-1)
    {
     union_set(disset[x],y);
    }
    else
    disset[x]=y;//这个过程中只要状对象就行,矛盾在于对象
    if(disset[y]!=-1)
    {
     union_set(x,disset[y]);
    }
    else
    disset[y]=x;
   }
 //  union_set(x,y);
  }
  printf("Scenario #%d:/n",p++);
  if(flag)
  printf("Suspicious bugs found!/n/n");
  else
  printf("No suspicious bugs found!/n/n");
 }
 return 0;
}