zoukankan      html  css  js  c++  java
  • 优先队列实现哈弗曼最小权值

    建立哈弗曼树要求我们每次都选频率权值最小的点构成节点,即权值小的点在树的深处,权值大的点在树的浅处,根据节点选择的特点,我们可以把节点的值放在优先队列中,包括新形成的节点。

    我们先定义优先队列的优先级别。

    1 struct cmp
    2 {
    3    bool operator()(const int &a,const int &b)
    4    {
    5        return a>b;
    6    }
    7 };//最小值优先出队

    然后就是实现的整个程序。

    #include<stdio.h>
    #include<string.h>
    #include<algorithm>
    #include<iostream>
    #include<queue>
    #define maxn 50050
    using namespace std;
    struct cmp
    {
       bool operator()(const int &a,const int &b)
       {
           return a>b;
       }
    };
    int main()
    {
       int n;
       while(scanf("%d",&n)!=EOF)
       {
           int x;
           priority_queue<int,vector<int>,cmp>q;
           for(int i=0;i<n;i++)
           {
               scanf("%d",&x);
               q.push(x);
           }
           __int64 sum=0;
           while(q.size()!=1)
           {
               int a=q.top();
               q.pop();
               int b=q.top();
               q.pop();
               sum+=a+b;
               q.push(a+b);
    
           }
           printf("%I64d
    ",sum);
       }
       return 0;
    }

    练习题链接
    http://www.51nod.com/onlineJudge/questionCode.html#problemId=1117&noticeId=19046

  • 相关阅读:
    The Castle
    洛谷七月月赛
    Superprime Rib
    Leetcode 记录(201~300)
    03爬虫 爬取hfutxc成绩
    Leetcode 记录(101~200)
    LeetCode Weekly Contest 32
    Leetcode 记录(1~100)
    C++,java信息,文件传输
    毕业设计-自然场景下显著目标的检测
  • 原文地址:https://www.cnblogs.com/NaCl/p/4705922.html
Copyright © 2011-2022 走看看