代码
#include<iostream>
#include <string>
#include <queue>
#include <utility>
#include<cstring>
#include<stdlib.h>
#include <algorithm>
using namespace std;
typedef struct treenode{
char c;
int weight;
string huffcode;
treenode *lchild,*rchild;
treenode():lchild(NULL),rchild(NULL),c('\0'),weight(0),huffcode(""){}
}treenode;
struct cmp1 {
bool operator() (treenode *a, treenode * b) {
return a->weight > b->weight;
}
};
struct cmp2 {
bool operator() (treenode *a, treenode * b) {
return a->c > b->c;
}
};
priority_queue <treenode*,vector<treenode*>,cmp2 > res;
priority_queue <treenode*,vector<treenode*>,cmp1 > q;
void creatcode(treenode *t)
{
//cout<<t->weight<<endl;
if(t->lchild)
{
t->lchild->huffcode = t->huffcode+"0";
creatcode(t->lchild);
}
if(!(t->lchild)&&!(t->rchild))
{
res.push(t);
/*a[cnt++].c=t->c;
a[cnt++].huffcode=t->huffcode;*/
}
if(t->rchild)
{
t->rchild->huffcode=t->huffcode+"1";
creatcode(t->rchild);
}
}
int main()
{
char st[10];
int x;
while(cin>>st)
{
x=0;
for (int i = 2; i < strlen(st); i ++ )
{
x=x*10+st[i]-'0';
}
treenode *t=new treenode;
t->c=st[0];
//cout<<t->c<<' '<<x<<endl;
t->weight=x;
q.push(t);
}
//依次找出权值最小的两个结点
while(q.size()!=1)
{
treenode *x,*y;
x=q.top();
q.pop();
y=q.top();
q.pop();
//cout<<x->c<<' '<<x->weight<<' '<<y->c<<' '<<y->weight<<endl;
treenode *t= new treenode;
t->weight=x->weight+y->weight;
// cout<<t->weight<<endl;
t->lchild=x;
t->rchild=y;
q.push(t);
//cout<<q.top()->weight;
}
// cout<<q.top()->lchild->lchild->weight<<endl;
creatcode(q.top());
while(res.size())
{
cout<<res.top()->c<<':'<<res.top()->huffcode<<endl;
res.pop();
}
/*int len=sizeof(a)/sizeof(treenode);
sort(a,a+len);
for (int i = 0; i < 8; i ++ )
cout<<a[i].c<<':'<<a[i].huffcode<<endl;*/
}
有个问题找了特别久,就是结构体的初始化,不初始化会出现奇怪的bug,还是得把语法学好啊
以及本来想用个结构体存结果的,但不知为啥也报了错。。。干脆就再用个队列吧