hdu2527 Safe Or Unsafe(哈夫曼树水)

本文介绍了一种基于优先队列的编码压缩算法实现过程,通过不断合并出现频率最低的字符来减少编码长度,最终达到压缩的目的。文章详细展示了如何使用C++进行编码压缩,并通过实例解释了算法的工作原理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

每加一次相当于多一位编码。

#include <stdio.h>
#include <algorithm>
#include <iostream>
#include <queue>
#include <string.h>
using namespace std;

const int N = 50;
const int INF = 1000000;

struct node
{
    int w;
    friend bool operator < (const node &a, const node &b)
    {
        return a.w > b.w;
    }
};

int main()
{
  //  freopen("in.txt", "r", stdin);
    char s[5000];
    int a[30];
    int ans, C, num;
    scanf("%d", &C);
    while(C --)
    {
        cin >> num;
        scanf("%s", s);
        ans = 0;
        int len = strlen(s);
        memset(a, 0, sizeof(a));
        for(int i = 0; i < len; i ++)
            a[s[i] - 'a' + 1] ++;
        priority_queue <node> q;
        for(int i = 0; i < 27; i ++)
        {
            node tmp;
            tmp.w = a[i];
            if(tmp.w) q.push(tmp);
        }
        if(q.size() == 1) ans = len;//只有一种字符,每个字符一个字节,共len个
        else
        {
            while(q.size() > 1)
            {
                node tmp2, tmp3, tmp0;
                tmp2 = q.top();
                q.pop();
                tmp3 = q.top();
                q.pop();
                tmp0.w = tmp2.w + tmp3.w;
                ans += tmp2.w + tmp3.w;
                q.push(tmp0);
            }
        }
        if(ans < num) printf("yes\n");
        else printf("no\n");
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值