|
| 1 | +/* |
| 2 | + * This is a weighted quick union algorithm. |
| 3 | +*/ |
| 4 | +#include<iostream> |
| 5 | +#include<vector> |
| 6 | + |
| 7 | +using namespace std; |
| 8 | + |
| 9 | +#define whatis(x) cout<<#x<<": "<<x<<endl |
| 10 | +#define MAX 10000007 |
| 11 | + |
| 12 | +//For storing the root element |
| 13 | +//For storing the size of the root element |
| 14 | +int id[MAX]; |
| 15 | +int sz[MAX]; |
| 16 | + |
| 17 | +// initializing all the values of id[i] to i. |
| 18 | +// initializing all the values of sz[i] to 1; |
| 19 | +void initiate(){ |
| 20 | + for(int i = 0; i<MAX; i++ ) { |
| 21 | + id[i] = i; |
| 22 | + sz[i] = 1; |
| 23 | + } |
| 24 | +} |
| 25 | + |
| 26 | +// joining two nodes |
| 27 | +void join(int p, int q) { |
| 28 | + |
| 29 | + while(id[p] != p ) p = id[p]; |
| 30 | + while(id[q] != q) q = id[q]; |
| 31 | + |
| 32 | + if( p == q ) return ; |
| 33 | + |
| 34 | + if(sz[p] < sz[q]) { id[p] = q ; sz[q] += sz[p]; } |
| 35 | + else { id[q] = p; sz[p] += sz[q]; |
| 36 | + } |
| 37 | + |
| 38 | +} |
| 39 | + |
| 40 | +//Checking if the pair of nodes is already joined or not |
| 41 | +bool check_join( int p, int q) { |
| 42 | + |
| 43 | + |
| 44 | + while(id[p] != p ) p = id[p]; |
| 45 | + while(id[q] != q ) q = id[q]; |
| 46 | + |
| 47 | + |
| 48 | + if(p == q) return true; |
| 49 | + else return false; |
| 50 | +} |
| 51 | + |
| 52 | +//Example to show how it works |
| 53 | +void example() { |
| 54 | + |
| 55 | + int p[][2] = { |
| 56 | + {1, 2}, |
| 57 | + {2, 3}, |
| 58 | + |
| 59 | + }; |
| 60 | + |
| 61 | + int check[][2] = { |
| 62 | + {1, 3}, {1, 7} |
| 63 | + }; |
| 64 | + |
| 65 | + for(int i = 0; i<2; i++){ |
| 66 | + join(p[i][0], p[i][1]); |
| 67 | + } |
| 68 | + |
| 69 | + for(int i = 0 ; i<2; i++ ) { |
| 70 | + cout<<check_join(check[i][0], check[i][1])<<endl; |
| 71 | + } |
| 72 | + |
| 73 | +} |
| 74 | + |
| 75 | +/* |
| 76 | +1 as 1 and 3 are already joined. |
| 77 | +0 as 1 and 7 are not joined. |
| 78 | +*/ |
| 79 | + |
| 80 | +int main() { |
| 81 | + initiate(); //initiating id ans sz array above |
| 82 | + |
| 83 | + example(); // Taking an example |
| 84 | + |
| 85 | + return 0; |
| 86 | +} |
0 commit comments