--正文
k叉huffman
很自然想到huffman,不过果然不是简单的把k个最小的找出来就行
百度后才知道,如果这么干容易使最后的合并不足k次,所以需要添加若干个权值为0(不影响结果)的虚拟点,来进行合并
#include <iostream> #include <cstdio> #include <cstring> #include <algorithm> #include <queue> using namespace std; priority_queue<long long,vector<long long>,greater<long long> > q; int n,k; int main(){ while (scanf("%d %d",&n,&k) != EOF){ int i,j; for (i=1;i<=n;i++){ long long element; scanf("%lld",&element); q.push(element); } int more = 0; if ((n-1) % (k-1) != 0){ more = k-1-(n-1)%(k-1); for (i=1;i<=more;i++){ q.push(0); } } int total = n + more; long long res = 0; while (total >= 1){ long long sum = 0; for (i=1;i<=k;i++){ sum += q.top(); q.pop(); total --; if (total == 0) { break; } } res += sum; if (!q.empty()) { q.push(sum); total ++; } } printf("%lld\n",res); } return 0; }