quick-union

在无向图中判断连通

#include <iostream>
#include <cstdio>
using namespace std;

int main()
{
    int id[1000],p,q,i,j;
    for(i = 0;i < 1000;i ++ ) id[i] = i;
    while(scanf("%d%d",&p,&q) == 2)
    {
          for(i = p;i != id[i];i = id[i]);
          for(j = q;j != id[j];j = id[j])
          if(i == j) continue;
          id[i] = j;
          printf("%d %d\n",p,q);
    }
    return 0;
}


你可能感兴趣的:(quick-union)