PTA 05-树9 Huffman Codes

PTA 05-树9 Huffman Codes

原题链接

题目理解

【来自陈越姥姥的讲解视频和PPT+自己的记录】
(1)Huffman编码不唯一
0和1可能互换
树的形状可能不一样
但是都是最优Huffman编码
注意:最优编码不一定通过Huffman算法得到!
因此题意不能仅仅理解为:编码是否符合Huffman树

(2)HuffmanCodes的特点
1.最优编码——总长度(WPL)最小
2.无歧义解码——前缀码:数据仅存于叶子结点

3.没有度为1的结点——满足1,2则必然有3(题目不必单独判断)
满足2和3的不一定满足1,因此不可以通过23直接判断是否HuffanTree(不可以跳过建树判断最优编码)

计算WPL

MinHeap H=CreateHeap(H);//建立空的、容量为N的最小堆
H=ReadData(N);//将f[]读入H->Data中
HuffmanTree T=Huffman(H);//建立Huffman树
int CodeLen=WPL(T,0);//计算WPL

递归计算WPL:
思想:该结点的WPL=左结点的WPL+右节点的WPL

int WPL(HuffmanTree T,int Depth){
	if(!T->Left&&!T->Right){//叶子节点=哈弗曼结点 
		return T->Weight*Depth;
	}else{
		return (WPL(T->Left,Depth+1)+WPL(T->Right,Depth+1));
		//左右子树的WPL和,注意Depth+1 
	}
}

检查编码

(1)长度是否正确
Len=求和strlen(code[i])*f[i];
比较Len和WPL值
注意:Code[i]的最大长度为?
N-1
(斜树->肯定错)

(2)建树的过程中检查是否满足前缀码要求

Code

参考博文

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MINDATA -10001
#define ERROR NULL
//哈夫曼树结点
typedef struct TreeNode *HuffmanTree;
struct TreeNode{
	int Weight;
	HuffmanTree Left, Right;
};
 
//最小堆
typedef struct HNode *Heap;
typedef Heap MaxHeap;
typedef Heap MinHeap;
typedef TreeNode ElementType;	//堆中每个结点都是哈夫曼树结点的类型
struct HNode {
	ElementType *Data;
	int Size;
	int Capacity;
};
 
MinHeap CreateHeap( int MaxSize ) {
	MinHeap H = (MinHeap)malloc(sizeof(struct HNode));
	//因为0位置是哨兵,所以MaxSize+1
	H->Data = (ElementType *)malloc((MaxSize+1) * sizeof(ElementType));
	H->Size = 0;
	H->Capacity = MaxSize;
	H->Data[0].Weight = MINDATA;
	H->Data[0].Left = H->Data[0].Right = NULL;
	return H;
}
 
bool IsFull( MinHeap H ){
	return (H->Size == H->Capacity);
}
 
bool Insert( MinHeap H, HuffmanTree T ) {
	//将元素X插入堆,其中H->Data[0]已经定义为哨兵
	int i;
	if( IsFull(H) ){
		printf("最小堆已满");
		return false;
	}
	i = ++H->Size; //i指向插入后堆中最后一个元素的位置
	for( ; H->Data[i / 2].Weight > T->Weight; i /= 2)
		H->Data[i] = H->Data[i / 2];
	H->Data[i] = *T;
	return true;
}
 
bool IsEmpty( MinHeap H ) {
	return (H->Size == 0);
}
 
HuffmanTree DeleteMin( MinHeap H ) {
	//从最小堆H中取出键值最小的元素,并删除一个结点;
	int Parent, Child;
	ElementType X;
	HuffmanTree MinItem = (HuffmanTree)malloc(sizeof(struct TreeNode));
	if( IsEmpty(H) ){
		printf("最小堆已空");
		return ERROR;
	}
	*MinItem = H->Data[1]; //取出根节点存放最小值
	//用最小堆最后的一个元素从根结点开始向上过滤下层结点
	X = H->Data[H->Size--];
	for( Parent = 1; 2 * Parent <= H->Size; Parent = Child){
		//Child指向左右子结点的较小者
		Child = 2 * Parent;
		if( Child != H->Size && H->Data[Child].Weight > H->Data[Child + 1].Weight )
			Child++;
 
		if( X.Weight <= H->Data[Child].Weight ) break;	//找到了合适位置,要 >=
		else  //下滤
			H->Data[Parent] = H->Data[Child];
	}
	H->Data[Parent] = X;
	return MinItem;
}
 
 
HuffmanTree CreateHuffmanNode(int weight){
	HuffmanTree T = (HuffmanTree)malloc(sizeof(struct TreeNode));
	T->Weight = weight;
	T->Left = T->Right = NULL;
	return T;
}
HuffmanTree Huffman( MinHeap H ){
	//假设权值已经在H中,且已是最小堆形式
	int i;
	HuffmanTree T;
	for(i = 1; i < H->Capacity; i++) {  //是Capacity,不是Size;Size会变(错误原因)
		//printf("size:%d\n", H->Capacity);
		T = (HuffmanTree)malloc( sizeof(struct TreeNode) );
		T->Left = DeleteMin( H );
		T->Right = DeleteMin( H );
		T->Weight = T->Left->Weight + T->Right->Weight;
		//printf("l %d r %d\n", T->Left->Weight, T->Right->Weight);
		Insert( H, T );
		//printf("%d .\n", T->Weight);
	}
	T = DeleteMin( H );   //右边是个结点,左右孩子为空,不是一棵树(错误原因)
	//printf("%d .\n", T->Weight);
	return T;
}
 
int WPL( HuffmanTree T, int Depth ) {
	if( !T->Left && !T->Right )
		return ( Depth * T->Weight );
	else 
		return ( WPL(T->Left, Depth + 1) + WPL(T->Right, Depth + 1) );
}
 
MinHeap ReadData ( int n , int *f) {
	MinHeap H = CreateHeap(n);
	HuffmanTree T = (HuffmanTree)malloc( sizeof(struct TreeNode) );
	int data, i = 0;
	while ( n-- ) {
		getchar();	//第一次接收第一行的换行符,之后接收c[i]
		getchar();	//接收空格
		scanf("%d", &data);
		f[i++] = data;
		T->Weight = data;
		T->Left = T->Right = NULL;
		Insert( H, T );
	}
	free(T);
	return H;
}
 
void traverseHuffman ( HuffmanTree T ) {
	if( T ) {
	traverseHuffman( T->Left );
	printf("%d ", T->Weight);
	traverseHuffman( T->Right );
	}
}
 
void traverseHeap ( MinHeap H ) {
	for ( int i = 1; i <= H->Size; i++ ) {
		printf("%d ", H->Data[i].Weight);
	}
}
 
void DestroyTree ( HuffmanTree T ) {
	if ( T ) {
		DestroyTree( T->Left );
		DestroyTree( T->Right );
		free(T);
	}
}
 
bool Judge ( int N, int *f, int CodeLen ) {
	HuffmanTree T = (HuffmanTree)malloc(sizeof(struct TreeNode));
	HuffmanTree Tmp;
	T = CreateHuffmanNode(0);
	char code[64];
	int flag = 1, len, tmpN = N, wpl = 0, i = 0;
	while ( N-- ) {
		Tmp = T;
		getchar();
		getchar();
		scanf("%s", code);
		getchar();
		//printf("%s\n", code);
		len = strlen( code );
		wpl += len * f[i++];  //计算带权路径长度
		if ( flag && len > tmpN - 1 ) { //如果code长度大于N - 1
			flag = 0;
			//printf("1\n len : %d", len);
		}
		else if ( flag ) {
			for ( int i = 0; i < len; i++ ) {
				if ( i != len - 1 ) { //不是code的最后一位
					if ( code[i] == '1' ) {
						if ( !Tmp->Right )
							Tmp->Right = CreateHuffmanNode(0);
						else if ( Tmp->Right->Weight == 1 ) { //如果Tmp->Right已是带权节点
							flag = 0;
							//printf("2\n");
							break;
						}
						Tmp = Tmp->Right;
					}
					else {
						if ( !Tmp->Left )
							Tmp->Left = CreateHuffmanNode(0);
						else if ( Tmp->Left->Weight == 1 ) {
							flag = 0;
							//printf("3\n");
							break;
						}
						Tmp = Tmp->Left;
					}
				}
				else {
					if ( code[i] == '1' ) {
						if ( !Tmp->Right )
							Tmp->Right = CreateHuffmanNode(1);
						else { //Tmp->Right已存在,带权重复,不带权是前缀码
							flag = 0;
							//printf("4\n");
							break;
						}
						Tmp = Tmp->Right;
						if( Tmp->Right || Tmp->Left ) { //Tmp不是叶子结点
							flag = 0;
							//printf("5\n");
							break;
						}
					}
					else {
						if ( !Tmp->Left )
							Tmp->Left = CreateHuffmanNode(1);
						else {
							flag = 0;
							//printf("6\n");
							break;
						}
						Tmp = Tmp->Left;
						if( Tmp->Right || Tmp->Left ) {
							flag = 0;
							//printf("7\n");
							break;
						}
					}
				}
			}
		}
	}
	DestroyTree( T ); //释放刚建的哈夫曼树
	if ( flag && wpl == CodeLen )
		return true;
	else
		return false;
}
 
int main(){
	int N, M, CodeLen, *f;
	scanf("%d", &N);
	f = (int*)malloc( N * sizeof(int) );
	//建立堆和哈夫曼树
	MinHeap H;
	H = ReadData( N, f );
	HuffmanTree T = Huffman( H );
	CodeLen = WPL( T, 0 );
	//判断
	scanf("%d", &M);
	getchar();
	while ( M-- ) {
		if ( Judge( N, f, CodeLen ) ) {
			printf("Yes");
		}
		else {
			printf("No");
		}
        if(M!=0){
            printf("\n");//最后一行没换行
        }
	}
	return 0;
}

我的代码在输入上一直有个问题(maybe还有很多bug)

#include<iostream>
#include<map>
#include <stdio.h>
#include<string.h>
#include<stdlib.h>//malloc
#define HeapCapacity 64//最大63
#define MinData -1001
using namespace std;

typedef struct TreeNode *HuffmanTree;
struct TreeNode{
    int weight;
    HuffmanTree left,right;
};
typedef struct HeapNode *Minheap;
struct HeapNode{
    HuffmanTree *Element;//数组
    int size;
    int capacity;
};
map<int,int>mp;//记录频率,求权重

//建立最小堆
Minheap BuildMinHeap(int maxsize){
    Minheap H;
    H->Element=(HuffmanTree*)malloc((HeapCapacity)*sizeof(struct TreeNode));
    H->size=0;
    H->Element[0]->weight=MinData;//哨兵
    H->Element[0]->left=H->Element[0]->right=NULL;
    H->capacity=maxsize;
    return H;
}
//判断堆是否空
bool Isempty(Minheap H){
    return H->size==0?true:false;
}
//判断堆是否满
bool Isfull(Minheap H){
    return H->size==HeapCapacity?true:false;
}
//返回删除的最小结点
HuffmanTree DeleteHeap(Minheap H){
    HuffmanTree MinItem=(HuffmanTree)malloc(sizeof(struct TreeNode));
    MinItem=H->Element[1];//取最小权重的结点
    //用最小堆最后的一个元素从根结点开始向上过滤下层结点
    HuffmanTree X=H->Element[H->size--];//同时将size--
    int parent,child;
    //parent=1,顶点永远会被覆盖(删除),如果X直接是最小的话 54行H->Element[parent]=X;,H[1]就是X,否则,将逐步的选最小的孩子来代替parent值
    for(parent=1;parent*2<=H->size;parent=child){
        child=2*parent;
        //选值小的孩子
        if(H->Element[child]->weight>H->Element[child+1]->weight){
            child++;
        }
        if(X->weight<H->Element[child]->weight){
            break;
        }else{
            H->Element[parent]=H->Element[child];
        }
    }
    H->Element[parent]=X;
    return MinItem;
}
//将结点插入最小堆中
bool Insert(Minheap H,HuffmanTree T){
    if(Isfull(H)){//堆满无法插入
        return false;
    }
    int i;
    for(i=++H->size;H->Element[i/2]->weight>T->weight;i/=2){
        H->Element[i]=H->Element[i/2];
    }
    H->Element[i]=T;
    return true;
}
//建立huffman树
HuffmanTree BuildTree(Minheap H,int maxsize){
    HuffmanTree T;
    H=BuildMinHeap(maxsize);//建立最小堆
    while(!Isempty(H)){//当Heap不为空
        T=(HuffmanTree)malloc(sizeof(struct TreeNode));
        T->left=DeleteHeap(H);
        T->right=DeleteHeap(H);
        T->weight=T->left->weight+T->right->weight;
        Insert(H,T);//将结点插入Heap中
    }
    T=DeleteHeap(H);//建完树后头结点
    return T;
}
//计算WPL
int WPL(HuffmanTree T,int Depth){
    if(!T->left&&!T->right){//叶子结点
        return Depth*T->weight;
    }else{
        return WPL(T->left,Depth+1)+WPL(T->right,Depth+1);//递归计算左右子树的WPL和
    }
}
//创建带权值的Hufman结点
HuffmanTree CreateHuffmanNode(int weight){
    HuffmanTree T=(HuffmanTree)malloc(sizeof(struct TreeNode));
    T->weight=weight;
    T->left=T->right=NULL;
    return T;
}
//读字符和频率+建立最小堆【有问题】
Minheap ReadData(int n){
    Minheap H=BuildMinHeap(n);
    HuffmanTree temp=(HuffmanTree)malloc( sizeof(struct TreeNode) );
    getchar();	//第一次接收第一行的换行符,之后接收c[i]
    for(int i=0;i<n;i++){
    	char ch;
    	int fre;
    	if(i==0){
    		cin>>ch>>fre;
		}else{
			scanf(" %c %d",&ch,&fre);
		}
        mp[ch]=fre;//记录频率
        temp->weight=fre;//建最小堆
        temp->left=temp->right=NULL;
        Insert(H,temp);
    }
    free(temp);
    return H;
}
//删除树
void destroyTree(HuffmanTree T){
    if(T->left){
        destroyTree(T->left);
    }
    if(T->right){
        destroyTree(T->right);
    }
    free(T);
}
//判断编码是否最优且不是前缀
bool Judge(int N,int WPLweight){
    HuffmanTree T,temp;
    T=CreateHuffmanNode(0);
    char c,code[HeapCapacity];//存code
    int flag=1;//判断这个code是不是符合要求
    int len,wpl=0,maxN=N;
    while(N--){//对每个code进行判断
        cin>>c>>code;
        temp=T;
        len=strlen(code);//编码长度=树高
        wpl+=len*mp[c];//求WPL
        if(flag&&len>maxN-1){//flag原来为1,且编码长度大于N-1->不可能是最优编码
            flag=0;
        }else if(flag){//flag=1 暂时符合条件时->遍历code判断是否符合条件
            for(int i=0;i<len;i++){
                if(i!=len-1){//非叶子结点
                    if(code[i]=='1'){
                        if(!temp->right){//没有右子树->新建结点
                            temp->right=CreateHuffmanNode(0);
                        }else if(temp->right->weight==1){//有右子树且权重为1
                            flag=0;break;
                        }
                        temp=temp->right;
                    }else if(code[i]=='0'){
                        if(!temp->left){//没左子树->创建结点
                            temp->left=CreateHuffmanNode(0);
                        }else if(temp->left->weight==1){//已经是叶子结点
                            flag=0;break;
                        }
                        temp=temp->left;
                    }else{//出现别的编码
                        flag=0;break;
                   }
                }else{//最后一个code,叶子结点
                    if(code[i]=='1'){
                        if(!temp->right){//没有右子树->新建结点且权重为 1
                            temp->right=CreateHuffmanNode(1);
                        }else if(temp->right->weight==1){//有右子树且权重为1
                            flag=0;break;
                        }
                        temp=temp->right;
                    }else if(code[i]=='0'){
                         if(!temp->left){//没左子树->创建结点且权重为 1
                            temp->left=CreateHuffmanNode(1);
                        }else if(temp->left->weight==1){//已经是叶子结点
                            flag=0;break;
                        }
                        temp=temp->left;
                    }else{
                        flag=0;break;
                    }
                    if(temp->left||temp->right){//有一个不为0,即叶子结点还有左右孩子
                        flag=0;break;
                    }
                }
            }
        }
    }
    if(flag&&wpl==WPLweight){
        return true;
    }else{
        return false;
    }
}

int main(){
    Minheap H;
    int N,M,WPLweight;
    scanf("%d",&N);
    H=ReadData(N);
    HuffmanTree T=BuildTree(H,N);
    WPLweight=WPL(T,0);
    cout<<WPLweight<<endl;
    //判断
    scanf("%d",&M);
    while(M--){
        if(Judge(N,WPLweight)){
            printf("Yes");
        }else{
            printf("No");
        }
        if(M!=1){
            printf("\n");//最后一行没换行
        }
    }
    return 0;
}

目前发现的bug片段,如下。一直输入不进去。有路过的大神可以帮忙解决一下!感激不尽!

//读字符和频率+建立最小堆【有问题】
Minheap ReadData(int n){
    Minheap H=BuildMinHeap(n);
    HuffmanTree temp=(HuffmanTree)malloc( sizeof(struct TreeNode) );
    getchar();	//第一次接收第一行的换行符,之后接收c[i]
    for(int i=0;i<n;i++){
    	char ch;
    	int fre;
    	if(i==0){
    		cin>>ch>>fre;
		}else{
			scanf(" %c %d",&ch,&fre);
		}
        mp[ch]=fre;//记录频率
        temp->weight=fre;//建最小堆
        temp->left=temp->right=NULL;
        Insert(H,temp);
    }
    free(temp);
    return H;
}
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值