我们可以反过来想,如何将这几个线段组成一根 并且每次花费是组成的两段的和 

 

#include<bits/stdc++.h>
using namespace std;
#define maxn 50005
#define LL long long
LL  a[maxn],b[maxn],ans=0;
priority_queue<int,vector<int>,greater<int> >q;
int main(){
  LL  n;
  cin>>n;
  for(LL  j=1;j<=n;j++){
     scanf("%lld",&a[j]);
     q.push(a[j]);
  }
  LL ans=0;
  while(q.size()!=1){
     int l1=q.top();
     q.pop();
     int l2=q.top();
     q.pop();
     ans+=l1+l2;
     q.push(l1+l2);
  }
  cout<<ans<<endl;
  return 0;
}