#include<iostream>
#include<string>
#include<sstream>
#include<algorithm>
#include<queue>
using namespace std;
struct HufTree
{
char data;
int weight;
string code;
HufTree*left,*right;
HufTree(char d,int w):data(d),weight(w),code(""),left(0),right(0){}
};
struct cmp
{
bool operator() (HufTree* a ,HufTree* b)
{
return a->weight>b->weight; //与less是等价的
}
};
struct cmpGreat
{
bool operator() (HufTree* a ,HufTree* b)
{
return a->weight<b->weight; //与greater是等价的
}
};
void update0(HufTree*&root)
{
if(!root)
return;
root->code="0"+root->code;
update0(root->left);
update0(root->right);
}
void update1(HufTree*&root)
{
if(!root)
return;
root->code="1"+root->code;
update1(root->left);
update1(root->right);
}
priority_queue<HufTree*,vector<HufTree*>,cmpGreat> out;
void levelTra(HufTree*root)
{
if(!root)
return;
queue<HufTree* > q;
q.push(root);
while(!q.empty())
{
HufTree*pt=q.front();
if(!pt->left&&!pt->right)
out.push(pt);
q.pop();
if(pt->left)
q.push(pt->left);
if(pt->right)
q.push(pt->right);
}
}
int cont[120];
int main()
{
int num;
char code;
cin>>num;
while(num--)
{
cin>>code;
cont[code]++;
}
priority_queue<HufTree*,vector<HufTree*>,cmp> pq;
for(char i='A';i<='Z';i++)
if(cont[i]!=0)
pq.push(new HufTree(i,cont[i]));
int i=0;
while(!pq.empty()&&pq.size()>1)
{
HufTree* min1=pq.top();
pq.pop();
HufTree* min2=pq.top();
pq.pop();
HufTree* tem=new HufTree(' ',min1->weight+min2->weight);
tem->left=min1;
update0(tem->left);
tem->right=min2;
update1(tem->right);
pq.push(tem);
}
HufTree*root=pq.top();
levelTra(root);
while(!out.empty())
{
HufTree* tem=out.top();
cout<<tem->data<<" "<<tem->weight<<" "<<tem->code<<endl;
out.pop();
}
return 0;
}
实在是不会写oj了没想到这种通篇动态数据结构还真能过
sicily Huffman Coding V1
也能勉强算Huffman树模板类了