Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <bits/stdc++.h>
- using namespace std;
- class disjointSet
- {
- public:
- int *_rank, *parent,n;
- disjointSet(int n)
- {
- _rank = new int[n+1];
- parent = new int[n+1];
- this->n = n;
- MakeSet();
- }
- void MakeSet()
- {
- for(int i = 1; i <= n; i++)
- {
- parent[i] = i;
- _rank[i] = 0;
- }
- }
- void Union(int x, int y)
- {
- int xroot = Find(x);
- int yroot = Find(y);
- if(_rank[xroot] > _rank[yroot])
- {
- parent[yroot] = xroot;
- }
- else
- {
- parent[xroot] = yroot;
- if(_rank[x] == _rank[y])
- _rank[x] = _rank[x]+1;
- }
- }
- int Find(int x)
- {
- if(x != parent[x])
- {
- parent[x] = Find(parent[x]);
- }
- return parent[x];
- }
- };
- int main()
- {
- disjointSet obj(5);
- obj.Union(1,2);
- if(obj.Find(1) == obj.Find(1))
- cout << "1" << endl;
- else
- cout << "0" << endl;
- if(obj.Find(1) == obj.Find(3))
- {
- cout << "1" << endl;
- }
- else
- {
- cout << "0" << endl;
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement