#include <iostream>
#include <fstream>
#include <algorithm>
#include <queue>
using namespace std;
/*
每次选最小的k个元素进行合并。与2元Huffman算法类似
*/
int stone[50];
int greedyMax(int n, int k)
{
priority_queue<int> q;
int i;
for(i=0; i<n; i++)
q.push(stone[i]);
int sum = 0;
int max = 0;
while(q.size() > 2)
{
sum = 0;
for(i=0; i<2; i++)
{
sum += q.top();
q.pop();
}
max += sum;
q.push(sum);
}
while(!q.empty())
{
max += q.top();
q.pop();
}
return max;
}
int greedyMin(int n, int k)
{
priority_queue< int, vector<int>, greater<int> > q;
int i;
for(i=0; i<n; i++)
q.push(stone[i]);
int *a = new int[k];
int sum = 0;
int min = 0;
while(q.size() > k)
{
sum = 0;
for(i=0; i<k; i++)
{
sum += q.top();
q.pop();
}
min += sum;
q.push(sum);
}
while(!q.empty())
{
min += q.top();
q.pop();
}
return min;
}
int main()
{
ifstream fin("多元Huffman.txt");
cout << "输入石子堆数:";
int n;
fin >> n; cout << n;
cout << "\n输入每次最多合并的石子堆数:";
int k;
fin >> k; cout << k;
cout << "\n输入每堆石子的个数:\n";
int i;
for(i=0; i<n; i++)
{
fin >> stone[i];
cout << stone[i] << " ";
}
cout << "\n最大费用为:" << greedyMax(n, k);
cout << "\n最小费用为:" << greedyMin(n, k);
cout << endl;
fin.close();
return 0;
}
多元Huffman编码问题
最新推荐文章于 2023-04-30 22:28:09 发布