构造哈夫曼树,开始乱搞,蛤蛤。
时间复杂度: O(n∗log2n)
事实上正解应该是 O(n) ,蛤蛤。
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<queue>
const int MAXN = 500005;
typedef std::priority_queue<long long,std::vector<long long>,std::greater<long long> > Heap_ll;
int n, p[MAXN];
Heap_ll heap;
long long ans;
int main()
{
#ifndef ONLINE_JUDGE
freopen("sgu203.in","r",stdin);
freopen("sgu203.out","w",stdout);
#endif
scanf("%d",&n);
for(int i = 1; i <= n; i++)
scanf("%d",&p[i]), heap.push(p[i]);
for(int i = 1; i < n; i++)
{
long long a, b;
a = heap.top(), heap.pop();
b = heap.top(), heap.pop();
heap.push(a + b), ans += a + b;
}
printf("%I64d\n",ans);
#ifndef ONLINE_JUDGE
fclose(stdin);
fclose(stdout);
#endif
return 0;
}