HDU 2527 Safe Or Unsafe

这道题是哈弗曼编码问题,输入一个整数和一个字符串,对字符串中的字母操作,每个字母代表一个权值,权值为字母在串中的个数,相同的字母只算一个数值,如

h  e  l  l  o  w  o  r  l  d

1   1   3      2   1         1      1

哈弗曼编码的计算方式就是取两个最小的数先相加,然后放回,再取两个最小的数相加,重复操作至刚好取出两个数为止。

可用优先队列去模拟

如上述例子

1 1 1 1 1 2 3

1 1 1 2 2 3

1 2 2 2 3

2 2 3 3

3 3 4

4 6

10

sum = 2 + 2 + 3 + 4 + 6 + 10 = 27

有一个特殊情况就是当字符串仅形成一个数的时候,直接取这个数就好。

以下是代码实现


#include <stdio.h>
#include <iostream>
#include <queue>
#include <string.h>
using namespace std;
priority_queue<int, vector<int>, greater<int> > q;
int t, n, a[1000];
char str[1000];
int sum, b, c;
int main()
{
int i, j;
scanf("%d", &t);
while(t--)
{
scanf("%d%s", &n, str);
int m = strlen(str);
memset(a, 0, sizeof(a));
for(i = 0; i < m; i++)
{
a[str[i] - 'a']++;
}
for(i = 0; i < 26; i++)
{
if(a[i] != 0)
{
q.push(a[i]);
}
}
sum = 0;
while(!q.empty())
{
b = q.top();
q.pop();
if(!q.empty())
{
c = q.top();
q.pop();
sum += c + b;
q.push(b + c);
}
}
if(sum == 0)  
{
sum = b;
}
if(sum <= n)
printf("yes\n");
else
printf("no\n");
}
return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值