class DisjointSet{
public:
DisjointSet(int n)
{
m_pParent=NULL;
m_pRank=NULL;
m_n=n>0?n:1;
m_pParent=new int[m_n]{-1};
m_pRank=new int[m_n]{0};
for(int i=0;i<m_n;++i)
{
m_pParent[i]=-1;
m_pRank[i]=0;
}
}
virtual ~DisjointSet()
{
delete []m_pParent;
delete []m_pRank;
m_n=0;
}
int FindRoot(int x)
{
if(x<0||x>=m_n)
return -1;
int xRoot=x;
while(m_pParent[xRoot]!=-1)
xRoot=m_pParent[xRoot];
return xRoot;
}
bool Union(int x,int y)
{
int xRoot=FindRoot(x);
int yRoot=FindRoot(y);
if(xRoot==yRoot)
return false;
else
{
if(m_pRank[xRoot]>m_pRank[yRoot])
{
m_pParent[yRoot]=xRoot;
}
else if(m_pRank[xRoot]<m_pRank[yRoot])
{
m_pParent[xRoot]=yRoot;
}
else
{
m_pParent[xRoot]=yRoot;
m_pRank[yRoot]++;
}
}
return true;
}
private:
int*m_pParent;
int*m_pRank;
int m_n;
};