加权quickunion
#ifndef WEIGHTEDQUICKFIND_H_
#define WEIGHTEDQUICKFIND_H_
class UF
{
private :
int *id;
int *sz;
int count;
int length;
public:
UF (int N);
~UF ();
int UFcount ();
void UFunion (int p,int q);
bool UFconnected (int p,int q);
int UFfind (int p);
int UFlength (void);
};
#endif
#include "weightedquickunion.h"
UF::UF(int N)
{
id = new int [N];
count = N;
length = N;
for(int i = 0;i < N;i++)
{
id[i] = i;
sz[i] = 1;
}
}
UF::~UF()
{
delete [] id;
delete [] sz;
}
int UF::UFfind(int p)
{
while (p != id[p]) p = id[p];
return p;
}
bool UF::UFconnected(int p,int q)
{
return (this ->UFfind(p) == this ->UFfind (q) ) ? 1 : 0;
}
void UF::UFunion(int p,int q)
{
int pRoot = this -> UFfind (p);
int qRoot = this ->UFfind (q);
if (pRoot == qRoot) return ;
if (sz[pRoot] < sz[qRoot])
{
id[pRoot] = qRoot ;sz[qRoot] += sz[pRoot];
}
else
{
id[qRoot] = pRoot ;sz[pRoot] += sz[qRoot];
}
count -- ;
}
int UF::UFcount(void)
{
return count ;
}
int UF::UFlength(void)
{
return length;
}