图论--并查集---畅通工程

并查集用来判断图是否为连通图

#include
#include
using namespace std;

const int maxn=1000;
int father[maxn];
int height[maxn];

void Initial(int n)
{
  for(int i=0;i<=n;i++)
  {
    father[i]=i;
    height[i]=0;
  }
  return ;
}

int Find(int x)
{
  if(father[x]!=x)
  {
    father[x]=Find(father[x]);
  }
  return father[x];
}

void Union(int x,int y)
{
  x=Find(x);
  y=Find(y);
  if(x!=y)
  {
    if(height[x]<height[y])
    {
      father[x]=y;
    }else if(height[y]<height[x])
    {
      father[y]=x;
    }else
    {
      father[y]=x;
      height[x]++;
    }
    
  }
  return;
}

int main()
{
  int n,m;
  while(scanf("%d",&n)!=EOF)
  {
    scanf("%d",&m);
    if(n==0)
    break;
    Initial(n);
    for(int i=0;i<m;++i)
    {
      int x,y;
      scanf("%d",&x);
      scanf("%d",&y);
      Union(x,y);
    }
  
  int answer=-1;
  for(int i=1;i<=n;i++)
  {
    if(Find(i)==i)
    answer++;
  }

  printf("%d\n",answer);
  }

  return 0;
}

你可能感兴趣的:(图论)