/*
3
1 2 9
*/
#include <iostream>
const int maxn = 10000;
int t[maxn], e = 0;
#define KL(X) (X * 2 + 1)
#define KR(X) (X * 2 + 2)
#define P(X) (X / 2)
template <class T> void push(T x, T*, int&);
template <class T> T pop(T*, int&);
template <class T> void swap(T&, T&);
int main()
{
using namespace std;
int n, o;
cin >> n;
for (int i = 0; i < n; i++)
{
int x;
cin >> x;
push(x, t, e);
}
for (int i = 0; i < n - 1; i++)
{
// for (int j = 0; j < e; j++)
// {
// cout << t[j] << (j + 1 == e ? "\n" : " ");
// }
//
int k;
k = pop(t, e) + pop(t, e);
o += k;
push(k, t, e);
}
cout << o << endl;
return 0;
}
template <class T>
void push(T x, T* tt, int& ee)
{
int y;
y = ee++;
tt[y] = x;
while (y)
{
if (tt[P(y)] > tt[y]) swap(tt[P(y)], tt[y]);
else break;
y = P(y);
}
}
template <class T>
T pop(T* tt, int& ee)
{
int y = 0, o = tt[0];
tt[0] = tt[--ee];
while (true)
{
int z;
if (KR(y) < ee)
{
if (tt[KL(y)] > tt[KR(y)])
{
z = KR(y);
}
else
{
z = KL(y);
}
}
else if (KL(y) < ee)
{
z = KL(y);
}
else break;
if (tt[y] > tt[z])
{
swap(tt[y], tt[z]);
y = z;
}
else break;
}
return o;
}
template <class T>
void swap(T& a, T& b)
{
T c = a;
a = b;
b = c;
}
我甚至把测试数据下了也找不出问题。