Union find

#define MAXN 50001 int parent[MAXN];

int find(int X){ if (parent[X]==X) return X;   // this updates the parent[X] which speeds up a lot, // guaranteeing the next call to find(X) to be O(1) return parent[X] = find(parent[X]); }

void merge(int A, int B){ parent[find(A)] = find(B); }

int sameset(int A, int B){ return find(A) == find(B); }

void init(int N){ for (int i=0; i<=N; i++) parent[i] = i; }