poj3253
小根堆
#include <iostream> #include <stdio.h> #define M 20002 using namespace std; int A[M],len; void Min_Heap(int i) { int l=i<<1,r=l+1; int temp,least=i; if(l<=len&&A[l]<A[i]) { least=l; } if(r<=len&&A[r]<A[least]) { least=r; } if(least<=len&&least!=i) { temp=A[i];A[i]=A[least];A[least]=temp; Min_Heap(least); } } void Build_Min_Heap() { for (int i=len/2;i>=1;i--) { Min_Heap(i); } } void Min_Sort() { int temp; Build_Min_Heap(); while(len>=2) { temp=A[1];A[1]=A[len];A[len]=temp; len--; Min_Heap(1); } } int main() { int i,n,j; __int64 t,sum=0; scanf("%d",&n); len=n; for (i=1;i<=n;i++) { scanf("%d",&A[i]); } Min_Sort(); for (i=n;i>=2;i--) { t=A[i]+A[i-1]; j=i-2; while(j>=1&&t>A[j]) { A[j+1]=A[j];j--; } A[j+1]=t; sum+=t; } printf("%I64d\n",sum); return 0; }