Problem:
 Score: 400 points    Problem Statement  Quickly after finishing the tutorial of the online game ATChat , you have decided to visit a particular place with N-1 players who happen to be there. These N players, including you, are numbered 1 through N , and the friendliness of Player i is A_i .  The N players will arrive at the place one by one in some order. To make sure nobody gets lost, you have set the following rule: players who have already arrived there should form a circle, and a player who has just arrived there should cut into the circle somewhere.  When each player, except the first one to arrive, arrives at the place, the player gets comfort equal to the smaller of the friendliness of the clockwise adjacent player and that of the counter-clockwise adjacent player. The first player to arrive there gets the comfort of 0 .  What is the maximum total comfort the N players can get by optimally choosing the order of arrivals and the positions in the circle to cut into?      Constraints   All values in input are integers.  2 \leq N \leq 2 \times 10^5  1 \leq A_i \leq 10^9         Input  Input is given from Standard Input in the following format:  N  A_1  A_2  \dots  A_N       Output  Print the maximum total comfort the N players can get.        Sample Input 1 4
2 2 1 3      Sample Output 1 7  By arriving at the place in the order Player 4, 2, 1, 3 , and cutting into the circle as shown in the figure, they can get the total comfort of 7 .   They cannot get the total comfort greater than 7 , so the answer is 7 .       Sample Input 2 7
1 1 1 1 1 1 1      Sample Output 2 6

Solution (Python):




from __future__ import division, print_function 

import sys
import os
from collections import Counter, deque, defaultdict
import itertools
import math
import io


"""Uncomment modules according to your need"""













if sys.version_info[0] < 3:
    input = raw_input
    range = xrange

    filter = itertools.ifilter
    map = itertools.imap
    zip = itertools.izip



"""value of mod"""
MOD = 998244353
mod = 10**9 + 7

"""Uncomment next 4 lines if doing huge recursion"""




def prepare_factorial(mod=mod):
    """ returns two lists, factorial and inverse factorial modulo argument by default 10**9 +7 """
    
    fact = [1]
    for i in range(1, 200005):
        fact.append((fact[-1] * i) % mod)

    ifact = [0] * 200005
    ifact[200004] = pow(fact[200004], mod - 2, mod)
    for i in range(200004, 0, -1):
        ifact[i - 1] = (i * ifact[i]) % mod

    return fact, ifact

def modinv(n, p):
    """ returns N inverse modulo p """
    return pow(n, p - 2, p)

def ncr(n, r,  fact, ifact,MOD=mod):
    """ takes 4 arguments: n , r and factorial and inverse factorial lists"""
    t = (fact[n] * (ifact[r]*ifact[n-r]) % MOD)% MOD
    return t


def get_n(Sum):    
    """this function returns the maximum n for which Summation(n) <= Sum"""
    ans = (-1 + sqrt(1 + 8*Sum))//2
    return ans

def sieve(n):
    """ returns a list of prime numbers till n """
    if n < 2: return list()
    prime = [True for _ in range(n + 1)]
    p = 3
    while p * p <= n:
        if prime[p]:
            for i in range(p * 2, n + 1, p):
                prime[i] = False
        p += 2
    r = [2]
    for p in range(3, n + 1, 2):
        if prime[p]:
            r.append(p)
    return r



def divs(n, start=1):
    """ returns a list of all divisors till n """
    divisors = []
    
    for i in range(start, int(math.sqrt(n) + 1)):
        if n % i == 0:
            if n / i == i:
                divisors.append(i)
            else:
                divisors.extend([i, n // i])
    return divisors



def divn(n, primes):
    """ returns the number of divisors, two arguments n and the sieve till n """
    divs_number = 1
    for i in primes:
        if n == 1:
            return divs_number
        t = 1
        while n % i == 0:
            t += 1
            n //= i
        divs_number *= t
    return divs_number


def lrfind(d, x, default=-1):
    """ Takes 2 arguments an iterable and an element. returns a tuple (firstoccurence,lastoccurence) -1 if not found """
    left = right = -1
    for i in range(len(d)):
        if d[i] == x:
            if left == -1: left = i
            right = i
    if left == -1:
        return default, default
    else:
        return left, right

def gcd(x, y): 
    """ returns greatest common divisor of x and y """
    while y:
        x, y = y, x % y
    return x

def check_sorted(a):
    ''' returns True/False '''
    for i in range(len(a)-1):
        if a[i]>a[i+1]:
            return False
    return True

def print_arr2d(a):
    for i in a:
        prr(i)
    
def ceil(n, k=1): return n // k + (n % k != 0) 
def input(): return sys.stdin.readline().strip()
def ii(): return int(input()) 
def mi(): return map(int, input().split()) 
def li(): return list(map(int, input().split())) 
def lw(): return input().split() 
def lcm(a, b): return abs(a * b) // gcd(a, b) 
def prr(a, sep=' ', end='\n'): print(sep.join(map(str, a)), end=end) 
def dd(): return defaultdict(int) 
def ddl(): return defaultdict(list) 
def write(s): return sys.stdout.write(s)














def main(): 
    n=ii()
    a=li()
    a.sort(reverse=True)
    answer=0
    pointer=0
    pcount=0
    for i in range(1,n):
        answer+=a[pointer]
        if pointer==0:
            pointer+=1
        else:
            if pcount==1:
                pcount=0
                pointer+=1
            else:
                pcount+=1
    print(answer)


                

                    




        
    
        
        
    


            


            
                
            

            



                






        
        


    
    
                

    

""" -------- Python 2 and 3 footer by Pajenegod and c1729 ---------"""

py2 = round(0.5)
if py2:
    from future_builtins import ascii, filter, hex, map, oct, zip
    range = xrange

import os, sys
from io import IOBase, BytesIO

BUFSIZE = 8192

class FastIO(BytesIO):
    newlines = 0

    def __init__(self, file):
        self._file = file
        self._fd = file.fileno()
        self.writable = "x" in file.mode or "w" in file.mode
        self.write = super(FastIO, self).write if self.writable else None

    def _fill(self):
        s = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
        self.seek((self.tell(), self.seek(0, 2), super(FastIO, self).write(s))[0])
        return s

    def read(self):
        while self._fill(): pass
        return super(FastIO, self).read()

    def readline(self):
        while self.newlines == 0:
            s = self._fill();
            self.newlines = s.count(b"\n") + (not s)
        self.newlines -= 1
        return super(FastIO, self).readline()

    def flush(self):
        if self.writable:
            os.write(self._fd, self.getvalue())
            self.truncate(0), self.seek(0)


class IOWrapper(IOBase):

    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        if py2:
            self.write = self.buffer.write
            self.read = self.buffer.read
            self.readline = self.buffer.readline
        else:
            self.write = lambda s: self.buffer.write(s.encode('ascii'))
            self.read = lambda: self.buffer.read().decode('ascii')
            self.readline = lambda: self.buffer.readline().decode('ascii')


sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip('\r\n')



""" main function"""

if __name__ == '__main__':
    main()

Solution (Python):
n = int(input())

a = [int(i) for i in input().split()]

a.sort(reverse=True)

kotae = a[0]
for i in range(n-2):
    kotae += a[1 + (i // 2)]

print(kotae)

Solution (Python):
N=int(input())
A=list(map(int,input().split()))
A.sort(reverse=True)
ans=0
for i in range(1,N):
  ans+=A[i//2]
print(ans)

Solution (Python):
n, *a = map(int, open(0).read().split())
a.sort(reverse=True)
ans = a[0]
if n%2 == 0:
    for i in range(1, n//2):
        ans += a[i] * 2
else:
    for i in range(1, int(n/2)):
        ans += a[i] * 2
    ans += a[i+1]

print(ans)

Solution (Python):
import sys
def Ii():return int(sys.stdin.readline())
def Mi():return map(int,sys.stdin.readline().split())
def Li():return list(map(int,sys.stdin.readline().split()))

n = Ii()
a = sorted(Li(),reverse=True)
ans = a.pop(0)
for i in range(n//2-1):
  ans += 2*a[i]
  
if n%2 == 1:
  ans += a[i+1]  
  
print(ans)

Solution (Python):
def main():
    N = int(input())
    A = list(map(int, input().split()))
    A.sort(reverse=True)
    cnt = 1
    ans = A[0]
    if cnt == N - 1:
        print(ans)
        exit()
    flag = False
    for i in range(1,N):
        if cnt + 1 == N - 1:
            ans += A[i]
            break
        ans += A[i] * 2
        cnt += 2
        if cnt == N - 1:
            break

    print(ans)
    


if __name__ == "__main__":
    main()

Solution (Python):
n = int(input())
*a, = map(int,input().split())
a.sort(reverse = True)
ans = 0
n -= 1
if n % 2 == 0:
    z = (n-2)//2
    ans += a[0]
    for i in range(1, 1 + z):
        ans += 2 * a[i]
    ans += a[z+1]

if not n % 2 == 0:
    z = (n-1)//2
    ans += a[0]
    for i in range(1, 1 + z):
        ans += 2 * a[i]

print(ans)

Solution (Python):
import sys
input = sys.stdin.buffer.readline





def RD(): return sys.stdin.read()
def II(): return int(input())
def MI(): return map(int,input().split())
def MF(): return map(float,input().split())
def LI(): return list(map(int,input().split()))
def LF(): return list(map(float,input().split()))
def TI(): return tuple(map(int,input().split()))




def main():
	n=II()
	A=LI()
	A.sort(reverse=True)

	ans=A[0]
	ans+=2*sum(A[1:(n+1)//2-1])

	if n%2:
		ans+=A[n//2]
	elif n>3:
		ans+=2*A[(n-1)//2]

	print(ans)











if __name__ == "__main__":
	main()

Solution (Python):
N = int(input())
A = list(map(int,input().split()))
A.sort(reverse=True)
ans = 0
cnt = 0
while True:
    if cnt == 0:
        ans+= A[0]
    else:
        ans+=A[(cnt+1)//2]
    cnt+=1
    if cnt == N-1:
        break
print(ans)

Solution (Python):

n=int(input())
alist=list(map(int,input().split()))

alist.sort()

retrum=0

retrum+=alist.pop()
for i in range(n-2):
    if i%2==0:
        retrum+=alist[-1]
    if i%2==1:
        retrum+=alist.pop()
print(retrum)

Solution (Python):
import heapq
from collections import deque
b=[]
heapq.heapify(b)

n = int(input())
a = list(map(int, input().split()))
a.sort(reverse=True)
a = deque(a)

heapq.heappush(b,-1*a.popleft())
ans = 0

while len(a)>0:
  temp = a.popleft()
  point = -1*heapq.heappop(b)
  ans+=point
  heapq.heappush(b, -1*temp)
  heapq.heappush(b, -1*temp)
  
print(ans)

Solution (Python):
import sys
sys.setrecursionlimit(10 ** 7)



from collections import deque

import itertools
import heapq

def input():
    return sys.stdin.readline().rstrip()


def main():
    N = int(input())
    A = list(map(lambda x: -1*int(x),input().split()))
    heapq.heapify(A)
    l = deque()
 
    score =0
    c = heapq.heappop(A)
    l.append(c)
    for i in range(N-1):
        c = heapq.heappop(A)
        l.append(c)
        l.append(c)
        current =l.popleft()
        score +=current

    print(-score)


if __name__ == "__main__":
    main()

Solution (Python):
N = int(input())
A = list(map(int,input().split()))
A.sort(reverse=True)
i = 1
ans = A[0]
N -= 2
while N>0:
    if N>1:
        ans += 2*A[i]
        N -= 2
        i += 1
    else:
        ans += A[i]
        break
print(ans)

Solution (Python):
import heapq

n = int(input())
a = list(map(int,input().split()))
a.sort(reverse=True)

h=[]

heapq.heappush(h,a[0]*(-1))
ans = 0
for i in range(1,n):
    ans-=heapq.heappop(h)
    heapq.heappush(h,a[i]*(-1))
    heapq.heappush(h,a[i]*(-1))
print(ans)

Solution (Python):
n = int(input())
a = list(map(int, input().split()))
a=sorted(a,reverse=True)
ans=0
for i in range(n-1):
    if i<n//2:
        ans+=a[i]
    else:
        ans+=a[i-n//2+1]

print(ans)

Solution (Python):
N = int(input())
A = list(map(int, input().split()))
A.sort(reverse=True)
if N%2:
    print((A[0]+2*sum(A[1:N//2])+A[N//2]))
else:
    print((A[0]+2*sum(A[1:N//2])))

Solution (Python):
n=int(input())
a=list(map(int,input().split()))

def linked_merge_sort(l): 
    if len(l) == 1:
        return
    q, r = divmod(len(l), 2)
    left = [l.pop() for _ in range(q)]
    right = [l.pop() for _ in range(q + r)]
    
    linked_merge_sort(left)
    linked_merge_sort(right)
    
    left.reverse()
    right.reverse()
    while left and right:
        if left[-1] <= right[-1]:
            l.append(left.pop())
        else:
            l.append(right.pop())
    while left:
        l.append(left.pop())
    while right:
        l.append(right.pop())
    return

linked_merge_sort(a)
b=[0]*n
for i in range(n):
    b[i]=a[n-1-i]
ans=0
for i in range(1,n):
    ans+= b[(i//2)]
print(ans)

Solution (Python):
N = int(input())
A = list(map(int, input().split()))
sort_A = sorted(A, reverse=True)
Ans = 0

loop = N // 2
for i in range(loop):
  Ans = Ans + (sort_A[i] * 2) 

Ans = Ans - sort_A[0]

if N % 2 == 1:
  Ans = Ans + sort_A[(N-1) // 2]

print(Ans)

Solution (Python):
n,ais = int(raw_input()), map(int, raw_input().split())
ais.sort(key = lambda x:-x)
n -=2
s = 0
s += ais[0]
i = 1
while(n):
	s += ais[i]
	n-=1
	if n:
		s += ais[i]
		n -=1
	i+=1

print s

Solution (Python):
n = int(input())
a = list(map(int, input().split()))

a.sort(reverse=True)

ans = a[0]
n -= 1
for i in range(1, n):
    if n > 2:
        ans += a[i] * 2
        n -= 2
    elif n == 2:
        ans += a[i]
        n -= 1
    else:
        break

print(ans)

Solution (Python):
from heapq import heappush, heapreplace

n = int(input())
a = sorted(map(int, input().split()), reverse=True)
h = [-a[0]]
c = 0
for i in range(1, n):
    c += heapreplace(h, -a[i])
    heappush(h, -a[i])
print(-c)

Solution (Python):
import sys
import math
import fractions
from collections import deque
from collections import defaultdict
sys.setrecursionlimit(10**7)

N = int(input())
A = list(map(int, input().split()))
A.sort(reverse=True)
point = 0
point += A[0]

cnt = 1
for a in A[1:]:
    for _ in range(2):
        point += a
        cnt += 1
        if cnt == N-1:
            break
    if cnt == N-1:
        break

if N == 2:
    print(A[0])
else:
    print(point)

Solution (Python):
import sys
import heapq, math
from itertools import zip_longest, permutations, combinations, combinations_with_replacement
from itertools import accumulate, dropwhile, takewhile, groupby
from functools import lru_cache
from copy import deepcopy

N = int(input())

A = list(map(int, input().split()))
A.sort(reverse=True)

ans = 0
cur = 0
for i in range(N - 1):
    ans += A[cur]
    if i < 1:
        cur += 1
    elif i % 2 == 0:
        cur += 1

print(ans)

Solution (Python):
N = int(input())
A = list(map(int, input().split()))

A = sorted(A, reverse = True)

counter = A[0]

if N ==2:
    print(A[0])
    exit()

for i in range (1, N-1):
    if i%2 ==1:
        counter+=A[(i+1)//2]
    else:
        counter+=A[i//2]

print(counter)

Solution (Python):
N = int(input())
A = list(map(int, input().split()))

A.sort(reverse=True)

ans = 0
for i in range(1, N):
    ans += A[i // 2]
print(ans)

Solution (Python):
import sys
input=sys.stdin.readline
sys.setrecursionlimit(10 ** 8)
from itertools import accumulate
from itertools import permutations
from itertools import combinations
from collections import defaultdict
from collections import Counter
import fractions
import math
from collections import deque
from bisect import bisect_left
from bisect import bisect_right
from bisect import insort_left
import itertools
from heapq import heapify
from heapq import heappop
from heapq import heappush
import heapq
from copy import deepcopy
from decimal import Decimal
alf = list("abcdefghijklmnopqrstuvwxyz")
ALF = list("ABCDEFGHIJKLMNOPQRSTUVWXYZ")

INF = float("inf")


N = int(input())
A = list(map(int,input().split()))
A.sort(reverse =  True)
ans = A[0]
flag = 0
index = 1
for i in range(N-2):
    if flag == 0:
        ans += A[index]
        flag = 1
    else:
        ans += A[index]
        index += 1
        flag = 0
print(ans)

Solution (Python):


import sys

class DChatInACircle:
    def solve(self, tc=0):
        n = int(input())
        a = [int(_) for _ in input().split()]
        a.sort()
        it = [a[-1]]
        for i in range(n - 2, -1, -1):
            it.append(a[i])
            it.append(a[i])
        print(sum(it[:n - 1]))


solver = DChatInACircle()
input = sys.stdin.readline

solver.solve()

Solution (Python):




from __future__ import division, print_function

import os,sys
from io import BytesIO, IOBase

if sys.version_info[0] < 3:
    from __builtin__ import xrange as range
    from future_builtins import ascii, filter, hex, map, oct, zip


def ii():  return int(input())
def si():  return input()
def mi():  return map(int,input().strip().split(" "))
def msi(): return map(str,input().strip().split(" "))
def li():  return list(mi())

def dmain():
    sys.setrecursionlimit(1000000)
    threading.stack_size(1024000)
    thread = threading.Thread(target=main)
    thread.start()
    









abc='abcdefghijklmnopqrstuvwxyz'
abd={'a': 0, 'b': 1, 'c': 2, 'd': 3, 'e': 4, 'f': 5, 'g': 6, 'h': 7, 'i': 8, 'j': 9, 'k': 10, 'l': 11, 'm': 12, 'n': 13, 'o': 14, 'p': 15, 'q': 16, 'r': 17, 's': 18, 't': 19, 'u': 20, 'v': 21, 'w': 22, 'x': 23, 'y': 24, 'z': 25}
mod=1000000007

inf = float("inf")
vow=['a','e','i','o','u']
dx,dy=[-1,1,0,0],[0,0,1,-1]
def getKey(item): return item[1] 
def sort2(l):return sorted(l, key=getKey,reverse=True)
def d2(n,m,num):return [[num for x in range(m)] for y in range(n)]
def isPowerOfTwo (x): return (x and (not(x & (x - 1))) )
def decimalToBinary(n): return bin(n).replace("0b","")
def ntl(n):return [int(i) for i in str(n)]
def ncr(n,r): return factorial(n)//(factorial(r)*factorial(max(n-r,1)))

def ceil(x,y):
    if x%y==0:
        return x//y
    else:
        return x//y+1

def powerMod(x,y,p):
    res = 1
    x %= p
    while y > 0:
        if y&1:
            res = (res*x)%p
        y = y>>1
        x = (x*x)%p
    return res

def gcd(x, y):
    while y:
        x, y = y, x % y
    return x
    
def isPrime(n) : 
    if (n <= 1) : return False
    if (n <= 3) : return True
    if (n % 2 == 0 or n % 3 == 0) : return False
    i = 5
    while(i * i <= n) : 
        if (n % i == 0 or n % (i + 2) == 0) : 
            return False
        i = i + 6
    return True



def read():
    sys.stdin  = open('input.txt', 'r')  
    sys.stdout = open('output.txt', 'w') 




def main():
    


    



    n=ii()
    a=li()
    a.sort(reverse=True)
    ans=a[0]
    p=1
    for i in range(2,n,2):
        if i==n-1:
            ans+=a[p]
        else:
            ans+=2*a[p]
            p+=1

    print(ans)

















    









    











BUFSIZE = 8192


class FastIO(IOBase):
    newlines = 0

    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None

    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()

    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()

    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)


class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")


def print(*args, **kwargs):
    """Prints the values to a stream, or to sys.stdout by default."""
    sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout)
    at_start = True
    for x in args:
        if not at_start:
            file.write(sep)
        file.write(str(x))
        at_start = False
    file.write(kwargs.pop("end", "\n"))
    if kwargs.pop("flush", False):
        file.flush()


if sys.version_info[0] < 3:
    sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout)
else:
    sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)

input = lambda: sys.stdin.readline().rstrip("\r\n")




if __name__ == "__main__":
    
    main()

Solution (Python):

n = int(input())
a = sorted(map(int, input().split()))[::-1]
ans = 0
c = 0
while c < n - 1:
    ans += a[(c + 1) // 2]
    c += 1
print(ans)

Solution (Python):
N = int(input())
A = list(map(int,input().split()))
A.sort(reverse = True)
cft = 0
for i in range(N-1):
    cft += A[(i+1)//2]
print(cft)

Solution (Python):
import sys
sys.setrecursionlimit(500000)

def input():
    return sys.stdin.readline()[:-1]

def mi():
    return map(int, input().split())

def ii():
    return int(input())

def i2(n):
    tmp = [list(mi()) for i in range(n)]
    return [list(i) for i in zip(*tmp)]


def main():
    N = ii()
    A = list(mi())
    A.sort(reverse=True)
    ans = A[0]
    if N%2:
        ans += 2*sum(A[1:N//2+1])-A[N//2]
    else:
        ans += 2*sum(A[1:N//2])

    print(ans)


if __name__ == '__main__':
    main()

Solution (Python):
def main():
    N = int(input())
    friendly = list(map(int, input().split()))
 
    friendly.sort()
 
    ans = friendly[-1]
    
    FLAG = True
    index = N - 2
    
    
    for i in range(N - 2):
        if (FLAG):
            ans += friendly[index]
            FLAG = False
        else:
            ans += friendly[index]
            FLAG = True
            index -= 1
    
        
    print(ans)
 
if __name__ == '__main__':
    main()

Solution (Python):
N=int(input())
A=list(map(int,input().split()))
A.sort(reverse=True)
N-=1
if N%2==0:
    ans=sum(A[:(N//2+1)])+sum(A[1:N//2])
else:
    ans=sum(A[:(N//2+1)])+sum(A[1:(N//2+1)])
print(ans)

Solution (Python):

def main():
    n = int(input())
    al = list(map(int, input().split()))
    al.sort(reverse=True)
    ans = 0

    for i in range(n):
        ans += al[i//2]

    ans -= al[0]
    print(ans)


if __name__ == "__main__":
    main()

Solution (Python):

import sys, re
from collections import deque, defaultdict, Counter, OrderedDict
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, radians
from heapq import heappush, heappop, heapify, nlargest, nsmallest
def STR(): return list(input())
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
def list2d(a, b, c): return [[c] * b for i in range(a)]
def sortListWithIndex(listOfTuples, idx):   return (sorted(listOfTuples, key=lambda x: x[idx]))
def sortDictWithVal(passedDic):
    temp = sorted(passedDic.items(), key=lambda kv: (kv[1], kv[0]))
    toret = {}
    for tup in temp:
        toret[tup[0]] = tup[1]
    return toret
def sortDictWithKey(passedDic):
    return dict(OrderedDict(sorted(passedDic.items())))
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
mod = 10 ** 9 + 7

n = INT()

a = LIST()

a = sorted(a)[::-1]

ans = a[0]

a = a[1:]
i = 0
while(n-2>0):
    ans+=a[i]
    n-=1
    if(n-2==0):
        break
    ans+=a[i]
    i+=1
    n-=1
print(ans)

Solution (Python):
import sys

readline = sys.stdin.readline
MOD = 10 ** 9 + 7
INF = float('INF')
sys.setrecursionlimit(10 ** 5)

import heapq


class PriorityQueue:
    class Reverse:
        def __init__(self, val):
            self.val = val

        def __lt__(self, other):
            return self.val[0] > other.val[0]

        def __repr__(self):
            return repr(self.val)

    def __init__(self, x=None, desc=False):
        if not x:
            x = []
        if desc:
            for i in range(len(x)):
                x[i] = self.Reverse(x[i])
        self._desc = desc
        self._container = x
        heapq.heapify(self._container)

    @property
    def is_empty(self):
        return not self._container

    def pop(self):
        if self._desc:
            return heapq.heappop(self._container).val
        else:
            return heapq.heappop(self._container)

    def push(self, item):
        if self._desc:
            heapq.heappush(self._container, self.Reverse(item))
        else:
            heapq.heappush(self._container, item)

    def top(self):
        if self._desc:
            return self._container[0].val
        else:
            return self._container[0]

    def sum(self):
        return sum(self._container)

    def __len__(self):
        return len(self._container)


def main():
    def f(p, q):
        ret = (min(p, q), max(p, q))
        return ret

    n = int(readline())
    a = list(map(int, readline().split()))
    a.sort(reverse=True)
    ans = a[0]
    pq = PriorityQueue(desc=True)
    pq.push(f(a[0], a[1]))
    pq.push(f(a[0], a[1]))

    for x in a[2:]:
        first, second = pq.pop()
        ans += first
        pq.push(f(first, x))
        pq.push(f(second, x))

    print(ans)


if __name__ == '__main__':
    main()

Solution (Python):
import heapq

n = int(input())
arr = list(map(int,input().split()))

arr.sort()
arr.reverse()

que = [0]
heapq.heapify(que)

ans = 0

for i in range(n):
    top = heapq.heappop(que)
    top = -top
    ans += top
    if i == 0:
        heapq.heappush(que, -arr[i])
    else:
        heapq.heappush(que,-arr[i])
        heapq.heappush(que,-arr[i])

    

print(ans)

Solution (Python):
n = int(input())

a = list(map(int, input().split()))
a.sort(reverse=True)

ans = 0

for i in range(1, n):
    ans += a[i//2]

print(ans)

Solution (Python):

import sys
def main(N, A):
    A.sort(reverse=True)
    ans = A[0]
    for i in range(2, N):
        ans += A[i // 2]
    print(ans)

if __name__ == '__main__':
    input = sys.stdin.readline
    N = int(input())
    *A, = map(int, input().split())
    main(N, A)

Solution (Python):
import sys
readline = sys.stdin.readline
from collections import deque

def solve():
    N = int(readline())
    A = list(map(int, readline().split()))

    A.sort(reverse=True)

    q = deque()

    q.append(A[0])

    ans = 0
    for i in range(1, len(A)):
        v = q.popleft()
        ans += v
        q.append(A[i])
        q.append(A[i])

    print(ans)

solve()

Solution (Python):
N = int(input())
A = list(map(int, input().split()))
A.sort(reverse=True)
ans = 0
for i in range(1, N):
    ans += A[i // 2]
print(ans)

Solution (Python):
n = int(input())
a = list(map(int, input().split()))

newa = []

for num in a:
    newa.append(num)
    newa.append(num)

newa.sort(reverse=True)

ans=sum(newa[1:n])

print(ans)

Solution (Python):
'''
    Auther: ghoshashis545 Ashis Ghosh
    College: jalpaiguri Govt Enggineering College

'''
from os import path
import sys
from functools import cmp_to_key as ctk
from collections import deque,defaultdict as dd 
from bisect import bisect,bisect_left,bisect_right,insort,insort_left,insort_right
from itertools import permutations
from datetime import datetime
from math import ceil,sqrt,log,gcd
def ii():return int(input())
def si():return input()
def mi():return map(int,input().split())
def li():return list(mi())
abc='abcdefghijklmnopqrstuvwxyz'
mod=1000000007

inf = float("inf")
vow=['a','e','i','o','u']
dx,dy=[-1,1,0,0],[0,0,1,-1]

def bo(i):
    return ord(i)-ord('a')

file = 0

def solve():
    



    

    n=ii()
    a=li()
    a.sort(reverse=True)
    if(n==1):
        print(0)
        exit(0)
    ans=a[0]
    k=n-2
    for i in range(1,n):
        if(k==0):
            break
        if(k==1):
            ans+=a[i]
            k-=1
        else:
            ans+=2*a[i]
            k-=2
    print(ans)










  
















if __name__ =="__main__":

    if(file):

        if path.exists('input1.txt'):
            sys.stdin=open('input1.txt', 'r')
            sys.stdout=open('output1.txt','w')
        else:
            input=sys.stdin.readline
    solve()

Solution (Python):
import sys
input = sys.stdin.buffer.readline
N = int(input())
A = list(map(int, (input().split())))
A.sort(reverse=True)
if N%2:
    ans = A[0] + sum(A[1:(N-1)//2])*2 + A[(N-1)//2]
else:
    ans = A[0] + sum(A[1:N//2])*2
print(ans)

Solution (Python):
import sys
import heapq

input = sys.stdin.readline


def main():
    N = int(input())
    A = list(map(int, input().split()))

    A.sort(reverse=True)
    A = [-a for a in A]

    q = [A[0]]
    heapq.heapify(q)
    ans = 0
    for a in A[1:]:
        max_v = heapq.heappop(q)
        ans += max_v
        heapq.heappush(q, a)
        heapq.heappush(q, a)

    ans = -ans
    print(ans)


if __name__ == "__main__":
    main()

Solution (Python):
N = int(input())
A = list(map(int, input().split()))

A.sort()

count = 0
ans = 0

for idx, a in enumerate(reversed(A)):
    count += 1
    ans += a
    if count == N - 1:
        break
    if idx != 0:
        count += 1
        ans += a
    if count == N - 1:
        break
print(ans)

Solution (Python):
import heapq

n = int(input())
data = list(map(int, input().split()))
data.sort(reverse=True)

q = []
heapq.heappush(q, -data[1])
heapq.heappush(q, -data[1])
result = data[0]

for i in range(2, n):
    result += -heapq.heappop(q)
    heapq.heappush(q, -data[i])
    heapq.heappush(q, -data[i])

print(result)

Solution (Python):
def main():
    N = int(input())
    friendly = list(map(int, input().split()))

    friendly.sort()

    ans = friendly[-1]
    
    FLAG = True
    index = N - 2
    
    
    for i in range(N - 2):
        if (FLAG):
            ans += friendly[index]
            FLAG = False
        else:
            ans += friendly[index]
            FLAG = True
            index -= 1
    
        
    print(ans)

if __name__ == '__main__':
    main()

Solution (Python):
import sys
readline = sys.stdin.readline
sys.setrecursionlimit(10**8)
mod = 10**9+7

INF = 10**18
eps = 10**-7

N = int(readline())
A = list(map(int,readline().split()))

A.sort(reverse=True)
if N%2:
    print(2*sum(A[:(N+1)//2])-A[0]-A[N//2])
else:
    print(2*sum(A[:N//2])-A[0])

Solution (Python):
import sys
def rs(): return sys.stdin.readline().rstrip()
def ri(): return int(sys.stdin.readline())
def ria(): return list(map(int, sys.stdin.readline().split()))
def ws(s): sys.stdout.write(s); sys.stdout.write('\n')
def wi(n): sys.stdout.write(str(n)); sys.stdout.write('\n')
def wia(a, sep=' '): sys.stdout.write(sep.join([str(x) for x in a])); sys.stdout.write('\n')


import heapq

def solve(n, a):
    a = sorted(a, reverse=True)
    ans = 0

    h = [-a[0]]
    heapq.heapify(h)

    for i in range(1, n):
        p = heapq.heappop(h)
        ans += -p
        heapq.heappush(h, -a[i])
        heapq.heappush(h, -a[i])

    return ans


def main():
    n = ri()
    a = ria()
    wi(solve(n, a))


if __name__ == '__main__':
    main()

Solution (Python):
n=int(input())
A=list(map(int,input().split()))
A=list(reversed(sorted(A)))
ans=A[0]
for i in range((n-2)//2):
    ans+=2*A[i+1]
if n%2!=0:
    ans+=A[i+2]
print(ans)