Quick-union solution to connectivity problem
#include <iostream>
using namespace std;
const int N = 100;
int main()
{
int i, j;
int p, q, id[N];
for (i=0; i<N; i++)
{
id[i] = i;
}
while (cin>>p>>q)
{
// find the root of p
for (i=p; i != id[i]; i=id[i])
{
}
// find the root of q
for (j=q; j != id[j]; j=id[j])
{
}
if (i == j)
{
continue;
}
// quick union
id[i] = j;
cout<<p<<" "<<q<<endl;
}
system("pause");
return 0;
}
quick union测试用例图解如下:
quick union树表示图解如下: