zoukankan      html  css  js  c++  java
  • 哈夫曼树 ,堆算法

    输入一个 数n 代表叶节点数目

    输入n个叶节点的权重

    cnt建树,中序遍历输出每个叶节点的权重和哈夫曼码

    #include <iostream>
    #include<algorithm>
    #include<queue>

    using namespace std;
    struct node
    {
    int w;
    string ma;
    int lc;
    int rc;
    node()
    {
    ma.clear();
    lc=-1;
    rc=-1;
    }
    node(int x,int l,int r)
    {
    w=x;
    lc=l;
    rc=r;

    }
    bool operator <(const node& d)const
    {return w>d.w;}
    bool operator >(const node& d)const
    {return w<d.w;}

    };
    priority_queue<node> que;
    int sum;
    int cnt;
    node a[200];
    void dfs(int root,string t)
    { if(root==-1)
    return ;
    a[root].ma+=t;
    dfs(a[root].lc,t+"0");
    dfs(a[root].rc,t+"1");
    }
    void inorder(int root)
    {
    if(root==-1)
    return ;
    inorder(a[root].lc);
    if(a[root].lc==-1&&a[root].rc==-1)
    {

    cout<<a[root].w<<' '<<a[root].ma<<endl;
    sum++;
    }
    inorder(a[root].rc);
    }
    int main()
    {
    int n;
    cin>>n;
    for(int i=0;i<n;i++)
    {
    int x;
    cin>>x;
    que.push(node(x,-1,-1));
    }
    while(que.size()>1)
    {
    node x,y;
    x=que.top();
    que.pop();
    a[cnt++]=x;
    y=que.top();
    que.pop();
    a[cnt++]=y;
    que.push(node(x.w+y.w,cnt-2,cnt-1));
    }

    a[cnt]=que.top();
    int root=cnt;
    string t;
    t.clear();
    dfs(root,t);
    inorder(root);
    /* cout<<endl;
    cout<<sum<<endl;*/
    return 0;
    }

  • 相关阅读:
    epoll源码实现分析[整理]
    linux几种时间函数总结
    linux几种定时函数的使用
    linux下redis数据库的简单使用
    网络编程之非阻塞connect编写
    网络编程之select
    数码相框(LCD、I2C)
    centos tftp和samba的安装与配置
    libevent库简单使用
    c语言随机数
  • 原文地址:https://www.cnblogs.com/acmLLF/p/11938115.html
Copyright © 2011-2022 走看看