代码非原创 单纯作为笔记便于复习
代码
#include <iostream>
#include <cstring>
#include <vector>
#include <queue>
#include <cstdio>
#include <algorithm>
using namespace std;
const int maxn = 27;
int rec[maxn];//下标26个大写字母0-26,rec存储各字母权重
struct tree
{
char ch;//大写字母
int num;//权重即出现次数
tree * lchild;//左孩子
tree * rchild;//右孩子
tree(char cc = '@',int nn = 0):ch(cc),num(nn),lchild(NULL),rchild(NULL) {}
};
struct cmp//函数对象,作为比较函数用于优先队列
{
bool operator()(const tree *a,const tree* b)const
{
return a->num > b->num;
}
};
priority_queue<tree*,vector<tree*>,cmp> qu;
void createTree()
{
for(int i = 0 ; i < 26 ; i++)
{
if(rec[i])
{
tree * node = new tree;
node->num = rec[i];
node->ch = (char)(i+'A');
qu.push(node);
}
}
while(qu.size() > 1)
{
tree * f = qu.top();
qu.pop();
tree * s = qu.top();
qu.pop();
tree * tmp = new tree();//ch='@'
tmp->num = f->num + s->num;
tmp->lchild = f,tmp->rchild = s;
qu.push(tmp);
}
}
struct printTree
{
int num;
char ch;
string code;
~printTree() {}
};
vector<printTree> PT;
void print(tree* root, string res)
{
if(root == NULL)
return ;
if(root->ch != '@')
{
printTree pt;
pt.num = root->num;
pt.ch = root->ch;
pt.code = res;
PT.push_back(pt);
return;
}
print(root->lchild,res+"0");
print(root->rchild,res+"1");
delete root->lchild;
delete root->rchild;
}
bool cmp2(const printTree & a,const printTree & b)
{
return a.num > b.num;
}
int main()
{
// freopen("in.txt","r",stdin);
for(int i = 0 ; i < maxn ; i++)
rec[i] = 0;
int num;
cin >> num;
char ch;
for(int i = 0 ; i < num ; i++)
{
cin >> ch;
rec[ch-'A']++;
}
createTree();
tree * root = qu.top();
qu.pop();
print(root,"");
sort(PT.begin(),PT.end(),cmp2);
for(size_t i = 0 ; i < PT.size(); i++)
{
cout << PT[i].ch << " " << PT[i].num << " " << PT[i].code << endl;
}
return 0;
}