• 大小: 4KB
    文件类型: .cpp
    金币: 1
    下载: 0 次
    发布日期: 2021-06-02
  • 语言: C/C++
  • 标签:

资源简介

霍夫曼编码,对输入的字符集和各个字符对应的权值,例如A={a,b,c,d,e,f,g,h},各个字符对应的权值为{5,29,7,8,14,23,3,11},求出每个字符的霍夫曼编码。 【输入形式】 输入若干个字符(1 <= n <= 26),其权值为int型。 输入数据的第一行的整数n,表示字符数;接下来的n行是字符集,一行一个字符;最后一行是各字符的权值,以空格分隔。 【输出形式】 每个字符(节点)的霍夫曼编码。参见样例输出。 【样例输入】 4 a b c d 1 3 7 22 【样例输出】 a:000 b:001 c:01   d:1 【样例说明】 提示: 1、将最小两个子树合并过程中一定要从前向后去查找两个最小子树,最小子树作为新结点的左子树,次小子树作为新结点的右子树,编码过程中左子树定义为0,右子树定义为1 2、另外:一般原则要求:  若有重复权值结点,原来森林中的结点优先选择(即深度小的结点优先,以确保最终总树深较浅并相对平衡)。新生成的权值和的结点后用。

资源截图

代码片段和文件信息

/*输入格式
字符数量
n:4
输入字符:abcd“注意要连着输入”
输入权值:1 3 7 22
*/
#include 
#include 
#include 
#include 
#include 
typedef char key_type;
/*用于赫夫曼树的结构体*/
 
using namespace std;
 
typedef struct Node
{
int weight;
key_type key;
struct Node *lchild *rchild;
}HFMNode*HFMTree;
/*用于链表的结构体*/
typedef struct link_node
{
HFMTree data;
struct link_node *next;
}LNode*link;
/*对链表的操作*/
void init_link(link *head);//初始化链表
void insert_link(link head HFMTree hfm);//向链表中插入一个元素,并按照权重排序
int delete_link(link headHFMTree *hfm);//依次删除链表中的数据,成功返回1,失败返回0
/*创建赫夫曼树str为关键字,w为对应的权重*/
int creat_hfmTree(HFMTree *rootchar str[]int w[]);
/*获取赫夫曼编码表,存储在数组code中*/
void hfmTree_code(HFMTree head int achar code[]);
/*译码译码结果存储在decode数组中code输入的报文*/
int hfmTree_decode(HFMTree headconst char code[]char decode[]);
int main()
{
int bi;
HFMTree root;
char str[1000000];
scanf(“%d“&b);
int *w=new int[b];
scanf(“%s“str);
for(i=0;i scanf(“%d“&w[i]);
}
creat_hfmTree(&root str w);

char code[1024] = { 0 };//用来存放编码表
hfmTree_code(root 1code);
cout < return 0;
}
 
void init_link(link *head)
{
(*head) = (link)malloc(sizeof(LNode));
(*head)->next = NULL;
(*head)->data = NULL;
}
 
void insert_link(link head HFMTree hfm)
{
assert(head != NULL);
/*先构造链表节点*/
link temp = (link)malloc(sizeof(LNode));
temp->next = NULL;
temp->data = hfm;
 
while (head->next != NULL && head->next->data->weight < hfm->weight)
{
head = head->next;
}
if (head->next == NULL)
{
head->next = temp;
}
else
{
temp->next = head->next;
head->next = temp;
}
}
 
int delete_link(link head HFMTree *hfm)
{
assert(head != NULL);
if (head->next == NULL)
return 0;
link temp = head->next;
head->next = temp->next;
*hfm = temp->data;
free(temp);
return 1;
}
 
int

评论

共有 条评论