把常用的并查集写下来备用:
注:第一个并查集操作转自他人博客.
1:
typedef struct _node
{
_node* parent;
int rank;
}node;
node *s[5000];
void makeSet(int x)
{
s[x]=new node;
s[x]->rank=0;
s[x]->parent=s[x];
}
node* findSet(node* s)
{
if(s!=s->parent)
{
s->parent=findSet(s->parent);
}
return s->parent;
}
void link(node *s1, node *s2)
{
if(s1==s2)
return;
if(s1->rank > s2->rank)
s2->parent=s1;
else
{
s1->parent=s2;
if(s1->rank==s2->rank)
s2->rank++;
}
}
void _union(node *s1, node *s2)
{
link(findSet(s1),findSet(s2));
}
2:
//并查集操作
//n 代表数据规模
//p[] 存放的是每一个数据的父节点
make_set(int x)
{
int i;
for(i=0;i<n;i++)
{
p[i]=i;
rank[i]=0;
}
}
link(int x,int y)
{
if(rank[x] > rank[y])
p[y]=x;
else
p[x]=y;
if(rank[x]==rank[y])
rank[y]++;
}
findset(int x)
{
if(x!=p[x])
p[x]=findset(p[x]);
return p[x];
}
union(int x,int y)
{
link(findset(x),findset(y));
}
3:
#define number 20
int find(int array[],int x)
{
while(array[x]>0)
x=array[x];
return x;
}
void operate()
{
int i,h,k;
int m,n;
int num[number];
for(i=0;i<number;i++)
num[i]=0;
n = find(num,h);
m = find(num,k);
if(m!=n)
{
num[n] = m;
//..oprate here..
}
}