题目是是给定一个字符串,求哈夫曼编码的最短长度,没有找到原题,故用HUD-2527来代替。
解题思路:思路是哈夫曼树的非叶子结点权值和为哈夫曼编码的最短长度,使用优先队列来实现。值得注意的是aaaa 的哈夫曼编码为其长度,为4。
#include <iostream>
#include <string>
#include <queue>
#include <cstring>
using namespace std;
priority_queue<int , vector<int>, greater<int> > q; //小的先出队
int list[26];
int main()
{
int n, m;
string str;
cin >> n;
while(n--)
{
cin >> m;
cin >> str;
while(!q.empty()) //清空
q.pop();
memset(list, 0, sizeof(list));
for(int i = 0; i < str.length(); i++)
list[str[i]-'a']++;
for(int i = 0; i < 26; i++)
if(list[i])
q.push(list[i]);
int ans = 0;
if(q.size() > 1)
while(q.size() > 1)
{
int x1 = q.top();
q.pop();
int x2 = q.top();
q.pop();
ans += (x1 + x2); //依次累加非叶子结点。
q.push(x1+x2);
}
else //4 aaaaa 哈夫曼编码为5输出no
ans = q.top();
if(ans <= m)
cout << "yes" << endl;
else
cout << "no" << endl;
}
return 0;
}