请输入编码的字符个数:
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
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;
}