哈夫曼编码,元素为指针的优先队列

http://blog.csdn.net/huangxy10/article/details/8029962


3.下面是将指针存在优先队列中的方式

struct Node
{
     short f;
     short d;
     short fishs;
     short times;
     short i;
}; 

struct PCmp
{
    bool operator () (Node const *x, Node const *y)
    {
        if(x->f == y->f)
            return x->i > y->i;
        return x->f < y->f;
    }
}; 

priority_queue, PCmp > Q;


注意:

小优先是>号。

大优先是<号。

反过来的。


#include
using namespace std;

string ans[30];

struct Node
{
    bool ye;
    char ch;
    int val;
    Node *ls,*rs;
    Node(char a,int b):ch(a),val(b)
    {
        ye=true;
        ls=rs=NULL;
    }
};

string str;

void print(Node *now)
{
    if(now->ye)
    {
        ans[now->ch-'a']=str;
        return;
    }
    str.push_back('0');
    print(now->ls);
    str[str.size()-1]='1';
    print(now->rs);
    str=str.substr(0,str.size()-1);
}

struct cmp
{
    bool operator ()  (Node const *a,Node const *b)
    {
        return a->val>b->val;
    }
};

int main()
{
    priority_queue,cmp>q;
    int n;
    scanf("%d",&n);
    char ch;
    int val;
    for(int i=1;i<=n;i++)
    {
        getchar();
        scanf("%c %d",&ch,&val);
        Node* temp=new Node(ch,val);
        q.push(temp);
    }
    while(1)
    {
        Node* a=q.top();
        q.pop();
        if(q.empty())
        {
            print(a);
            break;
        }
        Node* b=q.top();
        q.pop();
        Node* c=new Node(0,a->val+b->val);
        c->ye=false;
        c->ls=a;
        c->rs=b;
        q.push(c);
    }
    puts("");
    for(int i=0;i


你可能感兴趣的:(紫书-第8章-高效算法设计,其他,树)