文章

14

粉丝

230

获赞

23

访问

62.1k

头像
哈夫曼编码的坑
P1562
发布于2022年8月8日 11:16
阅读数 4.4k

思路:

  • 通过遍历字符串,统计各个字符的数量,利用map记录
  • 遍历map,将map的值(字符数量)加入优先队列
  • 常规操作,两个小的数字出队,加上的和 进入队列,直到队列长度为1
  • 坑就在于,队列的起始长度可能为1,所以需要单独处理

代码

#include <bits/stdc++.h>

using namespace std;


int main()
{

    priority_queue<int,vector<int>,greater<int>> q; //升序排列
    string str;

    while(cin>>str)
    {
        if(str=="END") break;
        map <char,int> m;
        map <char,int> ::iterator it;
        int len = str.size();
        for(int i=0; i<len; i++)
        {
            char c = str[i];
            m[c]++;

        }
        for(it =m.begin(); it!=m.end(); it++)
            q.push(it->second);
        int huffman = 0;
        if(q.size()==1) //队列的起始长度可能为1,所以需要单独处理
            huffman=len;
        while(q.size()>1)
        {
            int t1 = q.top();
            q.pop();
            int t2 = q.top();
            q.pop();
            int t3 = t1+t2;
            huffman+=t3;
            q...
登录查看完整内容


登录后发布评论

1 条评论
snake
2024年3月10日 12:34

yes

赞(0)