Huffman编码

请输入编码的字符个数:
8
请输入各字符及对应的出现频率:
a 78
c 23
e 65
1 109
r 34
7 89
d 23
t 56
result:
1 : 01
7 : 00
a : 110
c : 11111
d : 11110
e : 101
r : 1110

t : 100

#include <stdio.h>
#include <stdlib.h> 
#include <algorithm>
#include <queue>
using namespace std;
//定义结构体指针 
struct Node
{
	Node *lchild;
	Node *rchild;
	int f;
	char c;
};
//定义编码组成元素 
struct com{  
    bool operator ()(Node *a,Node *b){  
        return a->f >= b->f;
    }  
};  
//定义Huffman结构体 
struct fuhs
{
	char code[100];
	char c;
}symbol[100];
bool com1(fuhs a,fuhs b)
{
	return a.c<b.c;
} 
//创建二叉树 
Node *creat(Node *p1,Node *p2)
{
	Node *head;
	head=(Node *)malloc(sizeof(Node));
	head->f=p1->f+p2->f;
	head->lchild=p1;
	head->rchild=p2;
	head->c='%'; 
	return head;
}
int ans=0;
char bianhao[100];
//遍历树给出编码 
void build(Node *head,int in)
{
	if(head->lchild==NULL&&head->rchild==NULL)
	{
		symbol[ans].c=head->c;
		for(int i=0;i<in;i++)
		symbol[ans].code[i]=bianhao[i];
		symbol[ans].code[in]='\n';
		ans++;
		return ;
	}
	bianhao[in]='0';
	build(head->lchild,in+1);
	bianhao[in]='1';
	build(head->rchild,in+1);
}
//主函数 
int main()
{
	//优先队列进行存储 
	priority_queue<Node *,vector <Node *>, com>que;
	Node *word[100];
	int n;
	printf("请输入编码的字符个数:\n");
	scanf("%d",&n);
	getchar();
	printf("请输入各字符及对应的出现频率:\n");
	for(int i=0;i<n;i++)
	{
		word[i]=(Node *)malloc(sizeof(Node));
		word[i]->lchild=word[i]->rchild=NULL;
		scanf("%c %d",&word[i]->c,&word[i]->f);
		getchar();
		que.push(word[i]);
	}
	Node *head;
	while(que.size()!=1)
	{
		Node *p1=que.top();
		que.pop();
		Node *p2=que.top();
		que.pop();
		head=creat(p1,p2);
		que.push(head);
	}
	build(head,0); 
	//排序 
	sort(symbol,symbol+n,com1);
	printf("result:\n");
	for(int i=0;i<n;i++)
	printf("%c : %s",symbol[i].c,symbol[i].code);
	return 0;
}

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值