哈夫曼树的构造
typedef struct HTNode *HuffmanTree;
struct HTNode
{
int Weight; /*结点权值*/
HuffmanTree Left;
HuffmanTree Right;
};
HuffmanTree Huffman(MinHeap H)
{
/*假设H->Size个权值已经存在H->Data[]->Weight里*/
int i,N;
HuffmanTree T;
BuildHeap(H); /*将H->Data[]按权值Weight调整为最小堆*/
N=H->Size;
for(i=1;i<N;i++) /*做H->Size-1次合并*/
{
T=(HuffmanTree)malloc(sizeof(struct HTNode));
T->Left=DeleteMin(H);
T->Right=DeleteMin(H);
T->Weight=T->Left->Weight+T->Right->Weight;
Insert(H,T);
}
return DeleteMin(H);
}
集合的数据结构
#define MAXN 1000
typedef int ElementType;
typedef int SetName;
typedef ElementType SetType[MAXN];
集合运算
(1)查找某个元素所在的集合(查找编号为X的元素所属的集合)
SetName Find(SetType S,ElementType X)
{
/*默认集合元素全部初始化为-1*/
for( : S[X]>=0;X=S[X]);
return X;
}
(2)集合的并运算
void Union(SetType S,SetName Root1,SetName Root2)
{
/*这里默认Root1和Root2是不同集合的根结点*/
S[Root2]=Root1;
}
(3)按秩合并
void Union(SetType S,SetName Root1,SetName Root2)
{
/*这里默认Root1和Root2是不同集合的根结点*/
/*保证小集合并入大集合*/
if(S[Root2]<S[Root1])
{
S[Root2]+=S[Root1];
S[Root1]=Root2;
}
else
{
S[Root1]+=S[Root2];
S[Root2]=Root1;
}
}
(4)路径压缩
SetName Find(SetType B,ElementType X)
{
/*默认集合元素全部初始化为-1*/
if(S[X]<0) return X;
else return S[X]=Find(S,S[X]);
}