这道题是哈弗曼编码问题,输入一个整数和一个字符串,对字符串中的字母操作,每个字母代表一个权值,权值为字母在串中的个数,相同的字母只算一个数值,如
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;
}