zoukankan      html  css  js  c++  java
  • nyist 801 Haffman编码 优先队列解决


    #include <cstdio>
    #include <queue>
    #include <cstring>
    #include <algorithm>
    using namespace std;

    struct Huffman{
    int father,r_child,l_child;
    char data;
    int path[65];
    int value,num,len;
    friend bool operator<(Huffman a,Huffman b){
    if(a.value==b.value)
    return a.data>b.data;
    return a.value>b.value;
    }
    }tree[130];
    priority_queue<Huffman> hf;

    bool cmp(Huffman a,Huffman b){

    return a.num<b.num;
    }

    void Create_Huffman(int n){

    int t=0;
    Huffman t1,t2,t3;
    while(hf.size()>1){
    t1 = hf.top();hf.pop();
    t2 = hf.top();hf.pop();
    t3.data=t1.data;
    t3.value = t1.value + t2.value;
    t3.l_child = t1.num;
    t3.r_child = t2.num;
    t3.father=-1;
    t1.father = t2.father = t3.num = n++;
    tree[t++] = t1;
    tree[t++] = t2;
    hf.push(t3);
    }
    tree[t++]=hf.top();
    hf.pop();
    }

    void Input_Path(int n){

    for(int i=0;i<n;i++){
    printf("%c:",tree[i].data);
    tree[i].len=0;
    int k=i,h;
    while(tree[k].father!=-1){
    h=tree[k].father;
    if(tree[h].l_child==k)
    tree[i].path[tree[i].len++] = 0;
    else
    tree[i].path[tree[i].len++] = 1;
    k=h;
    }
    for(int j=tree[i].len-1;j>=0;j--)
    printf("%d",tree[i].path[j]);
    printf(" ");
    }
    }

    int main(){

    int n;
    while(scanf("%d",&n)==1){
    if(n==0) continue;
    Huffman temp;
    for(int i=0;i<n;i++){
    getchar();
    scanf("%c%d",&temp.data,&temp.value);
    temp.num=i;
    temp.father=temp.l_child=temp.r_child=-1;
    hf.push(temp);
    }
    Create_Huffman(n);
    sort(tree,tree+2*n-1,cmp);
    Input_Path(n);
    }
    return 0;
    }

  • 相关阅读:
    数据库基本概念
    Python语言特性之5:自省
    Python语言特性之4:类变量和实例变量
    Python语言特性之3:@staticmethod和@classmethod
    Python语言特性之2:元类
    Python语言特性之1:函数参数传递
    基础数学与算法学习
    推荐系统资料
    MySQL相关
    Python科学计算包模块的安装(ubuntu)
  • 原文地址:https://www.cnblogs.com/huaixiaohai2015/p/5272438.html
Copyright © 2011-2022 走看看