Question:
给一串数,求出哈夫曼树的总代价
Solution:
贪心的哈夫曼思想,我们利用对来进行优先队列的维护
ps:本题中因为虽然限定了每个木块的长度在int型范围内,但是随着我们不断的加和,该数值会超过int的范围,所以说我们用long long 来八寸最后的统计结果,不然会爆掉
Code:
#include"iostream"
#include"cstdio"
#include"cstdlib"
#define N 21010
using namespace std;
long long heap[N];
long long n,heapnum,sum;
void swapk(long long x,long long y)
{
long long k=heap[x];
heap[x]=heap[y];
heap[y]=k;
}
void siftdown(int i)
{
int t=i;
while(i*2<=heapnum)
{
if(heap[i]>heap[i*2]) t=i*2;
else t=i;
if(i*2+1<=heapnum&&heap[i*2+1]<heap[t]) t=i*2+1;
if(i!=t)
{
swapk(i,t);
i=t;
}
else break;
}
}
int main()
{
scanf("%I64d",&n);
for(int i=1;i<=n;i++) scanf("%I64d",&heap[i]);
heapnum=n;
for(int i=n/2;i>=1;i--) siftdown(i);
sum=0;
while(heapnum>1)
{
long long k=heap[1];
heap[1]=heap[heapnum];
heapnum--;
siftdown(1);
k+=heap[1];
heap[1]=k;
siftdown(1);
sum+=k;
}
printf("%I64d\n",sum);
return 0;
}