Quick-Union

来源:互联网 发布:原油数据公布的网站 编辑:程序博客网 时间:2024/06/05 09:12

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 pfor (i=p; i != id[i]; i=id[i]){}// find the root of qfor (j=q; j != id[j]; j=id[j]){}if (i == j){continue;}// quick unionid[i] = j;cout<<p<<"  "<<q<<endl;}system("pause");return 0;}


quick union测试用例图解如下:

 

quick union树表示图解如下: