参考博客https://blog.youkuaiyun.com/galesaur_wcy/article/details/84393051
多元Huffman编码问题
Time Limit: 1000 ms Memory Limit: 65536 KiB
Problem Description
在一个操场的四周摆放着n堆石子。现要将石子有次序地合并成一堆。规定每次至少选2 堆最多选k堆石子合并成新的一堆,合并的费用为新的一堆的石子数。试设计一个算法,计算出将n堆石子合并成一堆的最大总费用和最小总费用。
对于给定n堆石子,计算合并成一堆的最大总费用和最小总费用。
Input
输入数据的第1 行有2 个正整数n和k(n≤100000,k≤10000),表示有n堆石子,每次至少选2 堆最多选k堆石子合并。第2 行有n个数(每个数均不超过 100),分别表示每堆石子的个数。
Output
将计算出的最大总费用和最小总费用输出,两个整数之间用空格分开。
Sample Input
7 3
45 13 12 16 9 5 22
Sample Output
593 199
Hint
请注意数据范围是否可能爆 int。
样例为 7 5 --- 5 9 12 13 16 22 45的时候那么 最小值应该是148
#include<bits/stdc++.h>
using namespace std;
int main(){
int n, k, i, f, m;
long d=0, x=0, a;
priority_queue<long>p;
priority_queue<long, vector<long>, greater<long> >q;
cin>>n>>k;
for(i = 0; i < n; i++){
cin>>f;
p.push(f);
q.push(f);
}
if(n==1)d = p.top();
while(p.size()>1){
a = p.top();
p.pop();
a += p.top();
p.pop();
p.push(a);
d += a;
}
if(q.size()>k){ //情况最好的时候,一开始就k,不如最后再k
m = n;
while(m>k){
m = m - k + 1;
}
for(i = 0; i < k-m; i++){
q.push(0);
}
}
while(q.size()>k){
a = 0;
for(i = 0; i < k; i++){
a += q.top();
q.pop();
}
q.push(a);
x += a;
}
while(!q.empty()){
x += q.top();
q.pop();
}
cout<<d<<" "<<x<<endl;
}