这题利用哈夫曼编码的思想,每次从数组中取出两个最小的数(顺序无所谓),然后相加,将和累加到最终结果中,接着将两个数的和再放入数组中,相应的这两个和数就舍弃。如此反复,直到数组中只剩小一个元素,累加结果就是所求值。如果用朴素的哈夫曼编码,那么是o(2*n*n)的复杂度,时间消耗主要在查找两个最小的元素上,其中n会不断增加,最终达到2n-2,这样会超时。参考数据结构(教材)。这里,我们可以这样减小查找最小元素的时间。首先将数组排序(从小到大),然后直接取出最小的两个元素值,进行相应操作。接着将他们的和插入到其余的n-2个元素中,这样由于舍弃了刚才的两个元素,然后又插入了一个元素,一次循环,共减少一个元素。不断循环n-1次,即可求出结果。其时间复杂度为O(2*n*n),其中,n在不断变小,最终实际上只有2个元素,这样复杂度就变低了。采用这样的思想,可以用数组模拟,当然,也可以用优先队列实现。而且其实现更简洁。下面分别是数组模拟和优先队列实现的代码:
//数组模拟:
#include <stdio.h>
#include <stdlib.h>
#include <algorithm>
#define Max 20010
using namespace std;
__int64 record[Max];
__int64 ans;
int n;
int cmp(const void *p,const void *q){
return (*(__int64*)p)-(*(__int64*)q);
}
int main(){
scanf("%d",&n);
int i,j,k;
for(i=1;i<=n;i++)
scanf("%I64d",&record[i]);
qsort(record+1,n,sizeof(__int64),cmp);
ans=0;
for(i=1;i<=n-1;i++){
__int64 temp=record[i]+record[i+1];
ans+=temp;
for(j=i+2;j<=n;j++)
if(temp<=record[j])
break;
for(k=i+1;k<=j-2;k++)
record[k]=record[k+1];
record[j-1]=temp;
}
printf("%I64d\n",ans);
return 0;
}
//优先队列
#include <stdio.h>
#include <stdlib.h>
#include <queue>
#include <vector>
using namespace std;
int n;
class cmp{
public:
bool operator()(const __int64 a,const __int64 b){
return a>b;
}
};
int main(){
scanf("%d",&n);
priority_queue<__int64,vector<__int64>,cmp>Queue;
__int64 temp;
while(n--){
scanf("%I64d",&temp);
Queue.push(temp);
}
__int64 ans=0,vec;
while(Queue.size()>1){
vec=0;
vec+=Queue.top();
Queue.pop();
vec+=Queue.top();
Queue.pop();
ans+=vec;
Queue.push(vec);
}
printf("%I64d\n",ans);
return 0;
}