哈夫曼树还是比较实用的,又简单。
具体的实现方法:设一个优先级队列,频率越小的字母越优先。
每次都从队列中取出最前面两个元素,合并成一个新的元素。
直到元素只剩一个。
具体的实现细节看代码吧。
#include<iostream>
#include<vector>
#include<string>
#include<queue>
using namespace std;
typedef struct node
{
char m;
int v;
node *left,*right;
}node;
typedef struct comp
{
bool operator () (node *a,node *b)
{
return a->v>b->v;
}
}comp;
void outcode(node* T,string &s)//输出编码 用引用节约空间
{
if(T->left!=NULL)
{
s.push_back('0');
outcode(T->left,s);
s.pop_back();
}
if(T->right!=NULL)
{
s.push_back('1');
outcode(T->right,s);
s.pop_back();
}
if(T->left==NULL&&T->right==NULL)
{
cout<<T->m<<" "<<s<<endl;
}
}
int main()
{
int n;
cin>>n;
priority_queue<node*,vector<node*>,comp> q;//利用优先级队列
for(int i=0;i<n;i++)
{
node *temp=new node;
cin>>temp->m>>temp->v;
temp->left=temp->right=NULL;
q.push(temp);
}
while(q.size()>=2)//建树
{
node* temp=new node;
temp->v=q.top()->v;
temp->left=q.top();
q.pop();
temp->v+=q.top()->v;
temp->right=q.top();
q.pop();
q.push(temp);
}
string s="";
outcode(q.top(),s);//输出对应的编码
return 0;
}