本算法主要解决动态连通性一类问题,这里尽量用精炼简洁的话来阐述。
数据结构描述:
class UnionFind
{
public:
UnionFind(int n);
~UnionFind();
int Count();
virtual bool Connected(int p,int q)=0;
virtual void Union(int p,int q)=0;
protected:
int *id;
int sz;
int num;
};
UnionFind::UnionFind(int n)
{
this->num = this->sz = n;
this->id = new int[n];
for(int i=0; iid[i] = i;
}
};
UnionFind::~UnionFind()
{
delete this->id;
delete &this->num;
delete &this->sz;
};
int UnionFind::Count()
{
return this->num;
};
class QuickFind : public UnionFind
{
public:
QuickFind(int n);
bool Connected(int p,int q);
void Union(int p,int q);
};
QuickFind::QuickFind(int n):UnionFind(n) {};
bool QuickFind::Connected(int p,int q)
{
return this->id[p] == this->id[q];
};
void QuickFind::Union(int p,int q)
{
int k = this->id[q];
for(int i=0; isz; i++)
{
if(this->id[i]==k)
{
this->id[i]=this->id[p];
}
}
this->num--;
};
class QuickUnion : public UnionFind
{
public:
QuickUnion(int n);
bool Connected(int p,int q);
void Union(int p,int q);
protected:
int findRoot(int p);
};
QuickUnion::QuickUnion(int n):UnionFind(n) {};
int QuickUnion::findRoot(int p)
{
while(p!=this->id[p])
{
p = this->id[p];
}
return p;
};
bool QuickUnion::Connected(int p,int q)
{
return this->findRoot(p)==this->findRoot(q);
};
void QuickUnion::Union(int p,int q)
{
int i = this->findRoot(p);
int j = this->findRoot(q);
if (i == j)
{
return;
}
this->id[j] = this->id[i];
this->num--;
};
class WeightedQuickUnion : public QuickUnion
{
public:
WeightedQuickUnion(int n);
~WeightedQuickUnion();
void Union(int p,int q);
protected:
int findRoot(int p);
private:
int *sz;
};
WeightedQuickUnion::WeightedQuickUnion(int n):QuickUnion(n)
{
this->sz = new int[n];
for(int i=0; isz[i] = 1;
}
};
WeightedQuickUnion::~WeightedQuickUnion()
{
delete this->sz;
};
int WeightedQuickUnion::findRoot(int p)
{
while (p != this->id[p])
{
this->id[p] = this->id[this->id[p]];
p = this->id[p];
}
return p;
};
void WeightedQuickUnion::Union(int p,int q)
{
int i = this->findRoot(p);
int j = this->findRoot(q);
if (i == j)
{
return;
}
if (this->sz[i] < this->sz[j])
{
this->id[i] = j;
this->sz[j] += this->sz[i];
}
else
{
this->id[j] = i;
this->sz[i] += this->sz[j];
}
this->num--;
};