Haffman编码
来源:互联网 发布:java编程99乘法表 编辑:程序博客网 时间:2024/05/22 08:20
- 题目801
- 题目信息
- 运行结果
- 本题排行
- 讨论区
Haffman编码
- 描述
哈弗曼编码大家一定很熟悉吧(不熟悉也没关系,自己查去。。。)。现在给你一串字符以及它们所对应的权值,让你构造哈弗曼树,从而确定每个字符的哈弗曼编码。当然,这里有一些小规定:
1.规定哈弗曼树的左子树编码为0,右子树编码为1;
2.若两个字符权值相同,则ASCII码值小的字符为左孩子,大的为右孩子;
3.创建的新节点所代表的字符与它的左孩子的字符相同;
4.所有字符为ASCII码表上32-96之间的字符(即“ ”到“`”之间的字符)。
- 输入
- 输入包含多组数据(不超过100组)
每组数据第一行一个整数n,表示字符个数。接下来n行,每行有一个字符ch和一个整数weight,表示字符ch所对应的权值,中间用空格隔开。
输入数据保证每组测试数据的字符不会重复。 - 输出
- 对于每组测试数据,按照输入顺序输出相应的字符以及它们的哈弗曼编码结果,具体格式见样例。
- 样例输入
3a 10b 5c 84a 1b 1c 1d 1
- 样例输出
a:0b:10c:11a:00b:01c:10d:11
- 来源
- 原创
- 上传者
- TC_黄平
#include
#include
#include
#define N 30
#define M 2*N-1
typedef struct {
int weight;
int parent;
int lchild;
int rchild;
}HTnode,HTree[M+1];
typedef struct zi{
char n;//定义结构类型
}zi;
zi ch[55];
typedef char* HaCode[N+1];
void select(HTree ht,int n,int *p,int *q){
int min1=32767,min2=32767,t,i;
for(i=1;i<=n;i++)
if(ht[i].parent==0)
{
if(min1>ht[i].weight){
min1=ht[i].weight;
*p=i;
}
}
for(i=1;i<=n;i++)
if(ht[i].parent==0&&i!=*p)
{
if(min2>ht[i].weight&&i!=*p){//select函数
min2=ht[i].weight;
*q=i;
}
}
if(ht[*p].weight==ht[*q].weight&&ch[*p].n>ch[*q].n){
t=*q;
*q=*p;
*p=t;
}
}
void CrtHTree(HTree ht,int n){//建树
int i;
int s1,s2,m=2*n-1;
for(i=1;i<=n;i++){
scanf("\n%c%d",&ch[i].n,&ht[i].weight);
ht[i].parent=ht[i].lchild=ht[i].rchild=0;
}
for(i=n+1;i<=m;i++)
ht[i].weight=ht[i].parent=ht[i].lchild=ht[i].rchild=0;
for(i=n+1;i<=m;i++)
{
select(ht,i-1,&s1,&s2);
ht[i].weight=ht[s1].weight+ht[s2].weight;
ht[s1].parent=i;ht[s2].parent=i;
ht[i].lchild=s1;ht[i].rchild=s2;
}
}
void CrtHacode(HTree ht,HaCode hc,int n){//编码
char *cd;
int start,c,i,p;
cd=(char*)malloc(n*sizeof(char));
cd[n-1]='\0';
for(i=1;i<=n;i++){
start=n-1;
c=i;p=ht[i].parent;
while(p!=0){
--start;
if(ht[p].lchild==c)
cd[start]='0';
else
cd[start]='1';
c=p;p=ht[p].parent;
}
hc[i]=(char*)malloc(sizeof(char));
strcpy(hc[i],&cd[start]);
}
free(cd);
}
int main(){
int l,i;
HaCode hc;
HTree ht;
while(~scanf("%d",&l)){//主函数
CrtHTree(ht,l);
CrtHacode(ht,hc,l);
for(i=1;i<=l;i++)
printf("%c:%s\n",ch[i].n,hc[i]);
}
return 0;
}
//可能是指针或数组方面的用错了,测试数据没有问题,就是报错,可能是、。。。。。
- Haffman编码
- Haffman编码
- Haffman 编码
- NYOJ 801 Haffman编码
- nyoj 801 Haffman编码
- nyoj 801 Haffman编码
- haffman哈夫曼编码的实现
- 数据结构笔记--haffman树与haffman编码分析
- 使用haffman(哈夫曼)编码的简单压缩软件
- 使用haffman(哈夫曼)编码的简单压缩软件
- nyoj801 Haffman编码(优先队列实现)
- Haffman编码/译码——数据结构作业(二)
- java_实现Haffman树及其编码与解码
- Haffman应用
- haffman树
- Haffman Code
- haffman树的遍历
- haffman部分报告
- nyoj 5
- HDU3487 Play with Chain (Splay)
- 【NOIP2014 D1T2】【Vijos】P1906 联合权值 (硬编程)
- 【树形DP】【多叉转二叉】【poj 1947】Rebuilding Roads
- Squid详细配置实用文档
- Haffman编码
- Phoenix 4.x HBase 0.98.1安装
- C/C++语言中const的用法
- Struts与Hibernate整合将Session和Transaction放在Filter中
- 蛇形填数
- Pycharm远程连接服务器(windows下远程修改服务器代码)
- Python 模块大全(很详细!)
- 第16周项目2(1-1)-用指针玩字符串
- Course