#include<bits/stdc++.h>
using namespace std;
#define fr(i,a,b) for(int i=(a),_end_=(b);i<=_end_;i++)
struct tree{
    tree *l,*r,*f;
    int v,sl,sr;
    tree(){
        l=r=f=NULL;
        v=sl=sr=0;
    }
}*root,*k,*d;
tree* merge(tree *x,tree *y){
    if(x==NULL)return y;
    if(y==NULL)return x;
    if(x->v>y->v)
        swap(x,y);
    x->r=merge(x->r,y);
    x->sr++;
    if((x->sl)<(x->sr)){
        swap(x->l,x->r);
        swap(x->sl,x->sr);
    }
    return x;
}
void insert(int x){
    k=new tree;
    k->v=x;
    if(root==NULL)root=k;
    else root=merge(root,k);
}
int top(){
    if(root!=NULL)return root->v;
    return -1;
}
void pop(){
    if(root!=NULL)root=merge(root->l,root->r);
}
int n,a,b,ans;
int main(){
    root=NULL;
    scanf("%d",&n);
    fr(i,1,n){
        scanf("%d",&a);
        insert(a);
    }
    fr(i,1,n-1){
        a=top();
        pop();
        b=top();
        pop();
        ans+=a+b;
        insert(a+b);
    }
    printf("%d\n",ans);
    return 0;
}

results matching ""

    No results matching ""