#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <iostream>
#include <queue>
#include <algorithm>
#include <vector>
typedef char Bit;
typedef char* Bits;
typedef int Weight;
typedef char DataType;
typedef struct _BinTrNode BinTrNode,*pBinTrNode;
enum TAG{
LEAF = 0,
NON_LEAF = 1,
Null = 'A'-1,
};
struct _BinTrNode{
int tag;
union UReg{
DataType Ch;
}uReg;
Weight W;
struct _BinTrNode* LftChild;
struct _BinTrNode* RghtChild;
};
typedef pBinTrNode BinTr;
class CmpPred{
public:
bool operator()(const pBinTrNode &P,const pBinTrNode &Q)const
{
return P->W <= Q->W;
}
};
static BinTr _Creat_()
{
std::priority_queue<pBinTrNode,std::vector<pBinTrNode>,CmpPred> prQue;
int N;
std::cin >> N;
Weight W;
DataType Ch;
while(N--)
{
std::cin >> Ch >> W;
pBinTrNode p = (pBinTrNode)malloc(sizeof(BinTrNode));
p->W = W;
p->uReg.Ch = Ch;
p->LftChild = NULL;
p->RghtChild = NULL;
p->tag = TAG::LEAF;
prQue.push(p);
}
while(prQue.size() > 1)
{
pBinTrNode p = (pBinTrNode)malloc(sizeof(BinTrNode));
p->LftChild = NULL;
p->RghtChild = NULL;
p->tag = TAG::NON_LEAF;
p->uReg.Ch = Null;
p->LftChild = prQue.top();prQue.pop();
p->RghtChild = prQue.top();prQue.pop();
p->W = p->LftChild->W + p->RghtChild->W;
prQue.push(p);
}
return prQue.top();
}
static int _WPL(const BinTr t,int Depth);
static int WPL(const BinTr t)
{
if(t == NULL)return -1;
return _WPL(t,0);
}
static int _WPL(const BinTr t,int Depth)
{
if(!t)return 0;
if(t->LftChild == NULL && t->RghtChild == NULL)
return Depth*(t->W);
return _WPL(t->LftChild,Depth+1)+_WPL(t->RghtChild,Depth+1);
}
//N最大时:哈夫曼树完全偏斜 有N-1个外部路径中间节点
//因此长度最大为N-1
static void Destr(BinTr t)
{
if(t)
{
Destr(t->LftChild);
Destr(t->RghtChild);
free(t);
}
}
static bool Judge(int minWPL,const Bits BitsCol[],const int N)
{
BinTr t = (BinTr)malloc(sizeof(BinTrNode));
t->LftChild = NULL;t->RghtChild = NULL;
t->tag = TAG::NON_LEAF;
t->uReg.Ch = TAG::Null;
t->W = 0;
for(int i = 0;i < N;++i)
{
Bits p = BitsCol[i];
if(!strlen(p))
{
Destr(t);
return false;
}
BinTr q = t;
while((*p)!='\0')
{
if((*p) == '1')
{
if(q->RghtChild == NULL)
{
q->RghtChild = (BinTr)malloc(sizeof(BinTrNode));
q = q->RghtChild;
q->LftChild = NULL;
q->RghtChild = NULL;
q->tag = TAG::NON_LEAF;
}else{
if(q->RghtChild->tag == TAG::NON_LEAF)
{
q = q->RghtChild;
}else{
Destr(t);
return true;
}
}
}else{
if(q->LftChild == NULL)
{
q->LftChild = (BinTr)malloc(sizeof(BinTrNode));
q = q->LftChild;
q->LftChild = NULL;
q->LftChild = NULL;
q->tag = TAG::NON_LEAF;
}else{
if(q->LftChild->tag == TAG::NON_LEAF)
{
q = q->LftChild;
}else{
Destr(t);
return true;
}
}
}
++p;
}
if(q->LftChild == NULL && q->RghtChild == NULL)q->tag = TAG::LEAF;
else{
Destr(t);
return false;
}
}
Destr(t);
return true;
}
haffman编码正确性判定
最新推荐文章于 2024-09-26 21:10:57 发布