Quick-union solution to connectivity problem



👍 cat program11.in 
3 4
4 9
8 0
2 3
5 6
2 9
5 9
7 3
4 8
5 6
0 2
6 1

👍 g++ -std=c++11 program12.cpp
👍 ./a.out < program11.in 
 3 4
 4 9
 8 0
 2 3
 5 6
 5 9
 7 3
 4 8
 6 1

👍 cat program12.cpp 
#include <iostream>
using namespace std;
static const int N = 10000;
int main() {
  int i, j, p, q, id[N];
  for (i = 0; i < N; i++) id[i] = i;
  while (cin >> p >> q) {
    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;
    cout << " " << p 
         << " " << q << endl;
  }
}

    

ch 1.3 Union-Find Algorithms p15 of