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

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<Node*, vector<Node*>, PCmp > Q;


注意:

小优先是>号。

大优先是<号。

反过来的。


#include<bits/stdc++.h>
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<Node*,vector<Node*>,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<n;i++)
    {
        printf("%c ",i+'a');
        cout<<ans[i]<<endl;
    }
    return 0;
}

//输入
/*

6
a 45
b 13
c 12
d 16
e 9
f 5

*/

//输出
/*

a 0
b 101
c 100
d 111
e 1101
f 1100

*/


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值