问题 E: 捡石子(哈夫曼树思想)

来源:互联网 发布:2015全国交通事故数据 编辑:程序博客网 时间:2024/06/06 01:49


Problem  Link:http://139.129.36.234/problem.php?cid=1015&pid=4


问题 E: 捡石子

时间限制: 1 Sec  内存限制: 128 MB
提交: 19  解决: 18
[提交][状态][讨论版]

题目描述

在一个圆形操场的四周摆放着 n堆石子。 现要将石子有次序地合并成一堆。 规定每次选2 堆石子合并成新的一堆,合并的费用为新的一堆石子数。试设计一个算法,计算出将 n堆石子合并成一堆的最小总费用。

输入

输入数据第1行有1个正整数 n(1≤n≤1000),表示有 n堆石子,每次选2堆石子合并。第2行有 n个整数, 分别表示每堆石子的个数(每堆石子的取值范围为[1,1000]) 。

输出

数据输出为一行, 表示对应输入的最小总费用。

样例输入

745 13 12 16 9 5 22

样例输出

313


AC code:

#include<iostream>#include<algorithm>#include<stdio.h>#include<map>#include<math.h>#include<string.h>#include<queue>#include<vector>#include<set>#define LL long long#define exp 1e-9#define MAXN 1000010        using namespace std;int main( )  {  //freopen("D:\\in.txt","r",stdin);int n,i;LL sum,tmp,q1,q2;scanf("%d",&n);priority_queue<LL,vector<LL>,greater<LL> > pq;for(i=1;i<=n;i++){scanf("%lld",&tmp);pq.push(tmp);}sum=0;if(n==1){printf("%lld\n",tmp);}else{while(!pq.empty()){q1=pq.top();pq.pop();if(pq.empty()){printf("%lld\n",sum);break;}else{q2=pq.top();pq.pop();tmp=q1+q2;pq.push(tmp);sum+=tmp;}}}return 0;  }  


1 0