hdu 2527 Safe Or Unsafe(霍夫曼树)

本文介绍了一个有趣的编码问题,探讨如何通过哈夫曼编码确定字符串编码后的大小是否安全。使用哈夫曼树解决实际问题,帮助读者理解编码原理及其应用。

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

Safe Or Unsafe

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 1623    Accepted Submission(s): 644


Problem Description
Javac++ 一天在看计算机的书籍的时候,看到了一个有趣的东西!每一串字符都可以被编码成一些数字来储存信息,但是不同的编码方式得到的储存空间是不一样的!并且当储存空间大于一定的值的时候是不安全的!所以Javac++ 就想是否有一种方式是可以得到字符编码最小的空间值!显然这是可以的,因为书上有这一块内容--哈夫曼编码(Huffman Coding);一个字母的权值等于该字母在字符串中出现的频率。所以Javac++ 想让你帮忙,给你安全数值和一串字符串,并让你判断这个字符串是否是安全的?
 

Input
输入有多组case,首先是一个数字n表示有n组数据,然后每一组数据是有一个数值m(integer),和一串字符串没有空格只有包含小写字母组成!
 

Output
如果字符串的编码值小于等于给定的值则输出yes,否则输出no。
 

Sample Input
  
2 12 helloworld 66 ithinkyoucandoit
 

Sample Output
  
no yes
 

Source
 

Recommend
gaojie   |   We have carefully selected several similar problems for you:   2526  2522  2523  2524  2525 
题目分析:
霍夫曼树裸题
 
#include <iostream>
#include <cstring>
#include <cstdio>
#include <algorithm>
#include <queue>
#define MAX 100007

using namespace std;

int t,n;
char s[MAX];
int num[27];

struct Node
{
    int w;
    bool mark;
    Node ( int a , int b )
        :w(a),mark(b){}
    bool operator < ( const Node&a ) const
    {
        return w > a.w;
    }
};

int huffman ( )
{
    int sum = 0;
    priority_queue<Node> q;
    for ( int i = 0 ; i < 26 ; i++ )
        if ( num[i] ) q.push ( Node ( num[i] , false ) );
    if ( q.size() == 1 ) return q.top().w;
    while ( !q.empty() )
    {
        int w1 = q.top().w;
        if ( q.top().mark ) sum += w1;
        q.pop();
        if ( q.empty() ) break;
        int w2 = q.top().w;
        if ( q.top().mark ) sum += w2;
        q.pop ( );
        q.push ( Node ( w1+w2 , true ) );
    }
    return sum;
}

int main ( )
{
    scanf ( "%d" , &t );
    while ( t-- )
    {
        memset ( num , 0 , sizeof ( num ) );
        scanf ( "%d" , &n );
        scanf ( "%s" , s );
        int i = 0;
        while ( s[i] )
            num[s[i++]-'a']++;
        if ( huffman ( ) <= n ) puts ( "yes" );
        else puts ( "no" ); 
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值