An Introduction to Union Find : http://www.algorithmist.com/index.php/Union_Find
The most optimized implementation :
Code borrowed from : http://www.cs.princeton.edu/~rs/Algs3.cxx1-4/code.txt
The most optimized implementation :
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
static const int N = 10000; | |
int main() | |
{ int i, j, p, q, id[N], sz[N]; | |
for (i = 0; i < N; i++) | |
{ id[i] = i; sz[i] = 1; } | |
while (cin >> p >> q) | |
{ | |
for (i = p; i != id[i]; i = id[i]) | |
id[i] = id[id[i]]; | |
for (j = q; j != id[j]; j = id[j]) | |
id[j] = id[id[j]]; | |
if (i == j) continue; | |
if (sz[i] < sz[j]) | |
{ id[i] = j; sz[j] += sz[i]; } | |
else { id[j] = i; sz[i] += sz[j]; } | |
cout << " " << p << " " << q << endl; | |
} | |
} |
No comments:
Post a Comment