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):
N = int(input())
A = [int(i) for i in input().split()]
A.sort(reverse=True)
res = A[0]
i = 1
c = 2
while c < N:
    res = res + A[i]
    c = c + 1
    if c >= N:
        break
    res = res + A[i]
    c = c + 1
    if c >= N:
        break
    i = i + 1
    
print(res)

Solution (Python):
n=int(input())
a=sorted(map(int,input().split()),reverse=True)
p=0
for i in range(n//2):
    p+=a[i]
for i in range(1,n%2+n//2):
    p+=a[i]
print(p)

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

Solution (Python):
import sys
import numpy as np
import math  
from collections import deque
from collections import defaultdict
from copy import deepcopy
from itertools import accumulate 
def input(): return sys.stdin.readline().rstrip()
from functools import lru_cache 

def main():
    n = int(input())
    A = list(map(int,input().split()))
    A.sort(reverse=True)
    ans = A.pop(0)
    if n % 2 == 0: 
        ans += sum(A[: (n // 2 - 1)]) * 2
    else: 
        ans += sum(A[: (n // 2 - 1)]) * 2
        
        
        ans += A[n // 2 - 1]
    print(ans)
    return 0

if __name__ == "__main__":
    main()

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

A = list(map(int, input().split()))

A = A + A
A.sort(reverse=True)

print(sum(A[1:N]))

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()))
A = sorted(A)
ans = A[N//2:]
if N%2 == 0:
    print(sum(ans)*2 - max(ans))
else:
    print(sum(ans)*2 - max(ans) - min(ans))

Solution (Python):

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

asum=0
for i in range(1,n):
    ii=(i+2)//2

    asum+=a[ii-1]
    
print(asum)

Solution (Python):


from queue import Queue
from queue import LifoQueue as Stack
from math import sqrt, floor, ceil, log2, log10, pi
from fractions import gcd
from itertools import permutations, combinations
from operator import itemgetter
from functools import cmp_to_key


INF=1001001001
__MOD__=(10**9)+7
yn = 'YNeos'
judge = False
cnt = 0
ans = None


def lcm(a, b):
    return (a*b) // gcd(a,b)

def intinput():
    return int(input())

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

def lineinputs(func=intinput):
    datas = []
    while True:
        try:
            datas.append(func())
        except EOFError:
            break
    return datas

class ModInt():
    def __init__(self, x):
        self.__x = (x % __MOD__)
    def __add__(self, other):
        if type(other) == int:
            other = self.__class__(other)
            return int(self.__class__((self.__x + other.__x)%__MOD__))
        elif type(other) == ModInt:
            return self.__class__((self.__x + other.__x)%__MOD__)
        else:
            raise Exception("Not Int or Not ModInt")
    def __radd__(self, other):
        if type(other) == int:
            other = self.__class__(other)
            return int(self.__class__((other.__x + self.__x)%__MOD__))
        elif type(other) == ModInt:
            return self.__class__((other.__x + self.__x)%__MOD__)
        else:
            raise Exception("Not Int or Not ModInt")

    def __sub__(self, other):
        if type(other) == int:
            other = self.__class__(other)
            return int(self.__class__((self.__x - other.__x)%__MOD__))
        elif type(other) == ModInt:
            return self.__class__((self.__x - other.__x)%__MOD__)
        else:
            raise Exception("Not Int or Not ModInt")
    def __rsub__(self, other):
        if type(other) == int:
            other = self.__class__(other)
            return int(self.__class__((other.__x - self.__x)%__MOD__))
        elif type(other) == ModInt:
            return self.__class__((other.__x - self.__x)%__MOD__)
        else:
            raise Exception("Not Int or Not ModInt")

    def __mul__(self, other):
        if type(other) == int:
            other = self.__class__(other)
            return int(self.__class__((self.__x * other.__x)%__MOD__))
        elif type(other) == ModInt:
            return self.__class__((self.__x * other.__x)%__MOD__)
        else:
            raise Exception("Not Int or Not ModInt")
    def __rmul__(self, other):
        if type(other) == int:
            other = self.__class__(other)
            return int(self.__class__((other.__x * self.__x)%__MOD__))
        elif type(other) == ModInt:
            return self.__class__((other.__x * self.__x)%__MOD__)
        else:
            raise Exception("Not Int or Not ModInt")

    def __truediv__(self, other):
        if type(other) == int:
            other = self.__class__(other)
            return int(self.__class__((self.__x * other.__modinv())%__MOD__))
        elif type(other) == ModInt:
            return self.__class__((self.__x * other.__modinv())%__MOD__)
        else:
            raise Exception("Not Int or Not ModInt")
    def __rtruediv__(self, other):
        if type(other) == int:
            other = self.__class__(other)
            return int(self.__class__((other.__x * self.__modinv())%__MOD__))
        elif type(other) == ModInt:
            return self.__class__((other.__x * self.__modinv())%__MOD__)
        else:
            raise Exception("Not Int or Not ModInt")

    def __pow__(self, other):
        if type(other) == int:
            other = self.__class__(other)
            return int(self.__class__(pow(self.__x, other.__x, __MOD__)))
        elif type(other) == ModInt:
            return self.__class__(pow(self.__x, other.__x, __MOD__))
        else:
            raise Exception("Not Int or Not ModInt")
    def __rpow__(self, other):
        if type(other) == int:
            other = self.__class__(other)
            return int(self.__class__(pow(other.__x, self.__x, __MOD__)))
        elif type(other) == ModInt:
            return self.__class__(pow(other.__x, self.__x, __MOD__))
        else:
            raise Exception("Not Int or Not ModInt")

    def __modinv(self, m=__MOD__):
        a = self.__x
        if a == 0:
            raise ZeroDivisionError()
        if gcd(a, m) != 1:
            raise Exception("%sの逆数は求まりません。" % a)
        b, u, v = m, 1, 0
        while b != 0:
            t = a//b;
            a -= t*b
            a, b = b, a
            u -= t * v
            u, v = v, u
        u %= m
        if u < 0:
            u += m
        return u
    def __int__(self):
        return self.__x
    def __str__(self):
        return str(self.__x)



if __name__ == '__main__':
    N = intinput()
    a_arr = list(mulinputs())
    l = len(a_arr)
    is_odd = l % 2
    a_arr.sort(reverse=True)

    
    
    
    
    
    
    idx = 0
    ans = a_arr[idx]
    idx += 1
    for i in range(int(l//2)-1): ans += (a_arr[idx+i])*2
    if is_odd:
        idx += int(l//2)-1
        ans += a_arr[idx]
    print(ans)

Solution (Python):
import sys
from collections import defaultdict, Counter, deque
from itertools import accumulate, permutations, combinations
from operator import itemgetter
from bisect import bisect_left, bisect_right, bisect
from heapq import heappop, heappush
from fractions import gcd
from math import ceil, floor, sqrt, cos, sin, pi
from copy import deepcopy




def main():
    N = int(input())
    A = list(map(int, input().split()))
    A = sorted(A, reverse=True)
    ans = 0
    h = [-A.pop(0)]
    for a in A:
        t = heappop(h)
        ans += -t
        heappush(h,-a)
        heappush(h,-a)
    
    print(ans)

if __name__ == '__main__':
    main()

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

Solution (Python):
n = int(input())
goods = [int(x) for x in input().split()]

goods.sort(reverse=True)
score = 0

if len(goods) % 2 == 0:
    r = int(len(goods) / 2)
    score += goods[0]
    for i in range(1, r):
        score += goods[i] * 2
    
else:
    r = int((len(goods) - 1) / 2)
    score += goods[0]
    score += goods[r]
    for i in range(1, r):
        score += goods[i] * 2
print(score)

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

a = list(map(int, input().split()))

a = sorted(a,reverse = True)

co = 2
ans = a[0]
ind = 1

while True:
    if co + 1 < n:
        ans += a[ind] * 2
        co += 2
        ind += 1
    elif co + 1 == n:
        ans += a[ind]
        break
    else:
        break

print(ans)

Solution (Python):
x = int(input())
conf = list(map(int, input().split()))

conf.sort(reverse=True)

list=[]
list.append(conf[0])
conf.pop(0)
ans=0
re=1

for c in conf:
    ans+=list[0]
    list.append(c)
    re+=1
    if re==2:
        list.pop(0)
        re=0

print(ans)

Solution (Python):

import sys


def solve(N: int, A: "List[int]"):
    A.sort(reverse=True)
    count = -1 * A[0]
    rest = N

    for n in [0,0,1,1,2,2]:
        count += A[n]
        rest -= 1
        if rest == 0:
            print(count)
            return
    k = 2
    n = 3
    while True:
        for _ in range(3):
            for _ in range(k):
                count += A[n]
                rest -= 1
                if rest == 0:
                    print(count)
                    return
            n += 1
        k ** 2

    return



def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    N = int(next(tokens))  
    A = [int(next(tokens)) for _ in range(N)]  
    solve(N, A)

if __name__ == '__main__':
    main()

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

A.sort()
A = A[::-1]
ans = max(A)
M = (N-2)//2
for i in range(M):
    ans += 2*A[i+1]
if N%2 != 0:
    ans += A[M+1]
print(ans)

Solution (Python):
def mergesort(l):
    n = len(l)
    if(n == 1):
        return l
    elif(n <= 2):
        if(l[0] > l[1]):
            return [l[1],l[0]]
        else:
            return l
    else:
        tmp1 = mergesort(l[:n//2])
        tmp2 = mergesort(l[n//2:])
        x = n//2
        y = n-x
        l = []
        for i in range(n):
            if(tmp1[-x] < tmp2[-y]):
                l.append(tmp1[-x])
                x -= 1
            else:
                l.append(tmp2[-y])
                y -= 1
            if(x*y == 0):
                if(x == 0):
                    l += tmp2[-y:]
                else:
                    l += tmp1[-x:]
                break
        return l
n = int(input())
a = list(map(int,input().split()))
p = 0
a = mergesort(a)
if(n%2 == 0):
    for i in range(1,n//2+1):
        p += 2*a[-i]
    p -= a[-1]
else:
    for i in range(1,n//2+2):
        p += 2*a[-i]
    p -= a[-1]+a[-n//2]
print(p)

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

A.sort(reverse=True)

x = n // 2
y = n % 2
print(A[0] + sum(A[1:x]) * 2 + A[x] * y)

Solution (Python):
import sys
input = sys.stdin.readline
sys.setrecursionlimit(10 ** 7)

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

from collections import deque

a = deque(sorted(a, reverse=True))
ans = 0
first = a.popleft()
second = a.popleft()
ans += first
max_comfort = second
while True:
    if len(a) == 0:
        break
    ans += max_comfort
    a.pop()
    if len(a) == 0:
        break
    ans += max_comfort
    max_comfort = a.popleft()
print(ans)

Solution (Python):
import heapq

n, *aa = map(lambda x: -int(x), open(0).read().split())

aa.sort(reverse=True)

ans = 0

a = aa.pop()
b = aa.pop()
ans += min(a,b)

hq = [max(a,b)] * 2

heapq.heapify(hq)

while len(aa):
    ans += heapq.heappop(hq)

    tmp = aa.pop()
    heapq.heappush(hq, tmp)
    heapq.heappush(hq, tmp)

print(-ans)

Solution (Python):
N = int(raw_input())
A = (map(int, raw_input().split()))
A.sort(reverse=True)
j = 0
c = 1
ans = 0
for i in range(N-1):
  ans += A[j]
  c += 1
  if c == 2:
    c = 0
    j += 1
print ans

Solution (Python):
import sys
import itertools

import time
import math
import heapq
from collections import defaultdict
sys.setrecursionlimit(10 ** 7)
 
INF = 10 ** 9 + 7
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines



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

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

Solution (Python):
def main():
    n = int(input())
    comp = list(map(int, input().split()))
    comp.sort(reverse=True)
    
    fin = n - 2
    p = comp[0]
    for i in range(1, n):
        if fin == 1:
            p += comp[i]
            break
        elif fin == 0:
            break

        p += comp[i]*2
        fin -= 2

    print(p)

if __name__ == '__main__':
    main()

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

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

a.sort(reverse=True)
ans=a[0]
for i in range(n-2):
    ans+=a[i//2+1]
print(ans)

Solution (Python):
N = int(input())
As = sorted(list(map(int, input().split())), reverse = True)
ans = As[0]
N -= 2

p = N // 2
ans += sum(As[1:1+p]) * 2

if N % 2 == 1:
  ans += As[1+p]

print(ans)

Solution (Python):
def resolve():
    n = int(input())
    a = list(map(int, input().split()))
    a.sort(reverse=True)
    ans = 0
    for i in range(n):
        if i == 0: continue
        ans += a[i//2]
    print(ans)

resolve()

Solution (Python):
from collections import deque

N = int(input())
A = list(map(int, input().split()))
A.sort(reverse=True)
res = deque([A[0]])
ans = 0
for i in range(1, N):
    ans += res.popleft()
    res.append(A[i])
    res.append(A[i])
print(ans)

Solution (Python):
n = int(input())
A = list(map(int, input().split()))
A.sort(reverse=True)
ans = 0
ans += A[0]
if n > 2:

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

Solution (Python):
n = int(input())
a = list(map(int, input().split()))
a.sort()
print(sum(a[(n+1)//2:]) + sum(a[n//2:n-1]))

Solution (Python):
N=int(input())
a=list(map(int,input().split()))
A=sorted(a,reverse=True)
if N%2==1:
    s=A[0]+A[(N-1)//2]
    for i in range((N-1)//2-1):
        s+=A[i+1]*2
    print(s)
else:
    s=A[0]
    for i in range(N//2-1):
        s+=A[i+1]*2
    print(s)

Solution (Python):
import os
import sys
from io import BytesIO, IOBase





import heapq
def main():
    n = int(input())
    nums = list(map(int, input().split()))
    nums.sort(reverse=True)
    if n<=3:
        print(sum(nums[:n-1]))
        exit()
    

    hp = list()
    ans = 0
    
    heapq.heappush(hp, (-nums[1], nums[0]))
    heapq.heappush(hp, (-nums[2], nums[0]))
    heapq.heappush(hp, (-nums[2], nums[1]))
    ans = sum(nums[:2])

    i = 3
    while i < n:
        comfort, big = heapq.heappop(hp)
        ans += -comfort

        small = -comfort

        curr = nums[i] 

        
        heapq.heappush(hp, (-curr, small))
        heapq.heappush(hp, (-curr, big))
        i += 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")
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 = list(map(int, input().split()))

a.sort(reverse = True)
comfort = 0

if n%2 == 0:
    for i in range(n//2):
        if i == 0:
            comfort += a[i]
        else:
            comfort += 2*a[i]
    print(comfort)
else:
    for j in range((n-1)//2):
        if j == 0:
            comfort += a[j]
        else:
            comfort += 2*a[j]
        if j == ((n-1)//2-1):
            comfort += a[j+1]
    print(comfort)

Solution (Python):
N = int(input())
A = sorted(list(map(int, input().split())), reverse=True)
ans = max(A)
for i in range(2, N):
    if i % 2:
        ans += A[(i - 1) // 2]
    else:
        ans += A[i // 2]
print(ans)

Solution (Python):
from collections import deque
n = int(input())
a = sorted(deque(map(int, input().split())))

ans = a.pop()
if n % 2 == 0:
    l = (n-2)//2
else:
    l = (n-2)//2+1

for i in range(l):
    if n % 2 == 1 and i == l-1:
        ans += a.pop()
    else:
        ans += a.pop()*2
print(ans)

Solution (Python):
def resolve():
    from collections import deque
    n = int(input())
    a = list(map(int, input().split()))
    a = sorted(a)[::-1]
    nxt = deque([a[0]])
    ans = 0
    for i in range(1,n):
        b = nxt.popleft()
        ans += b
        nxt.append(a[i])
        nxt.append(a[i])

    print(ans)
resolve()

Solution (Python):
N = int(input())
A = sorted(list(map(int, input().split())), reverse=True)
sumA = 0
for x in range(N):
    if x == 0:
        sumA += 0
    elif x == 1:
        sumA += A[0]
    else:
        div, mod = divmod(x - 1, 2)
        sumA += A[div + mod]
print(sumA)

Solution (Python):
n = int(input())
li = list(map(int,input().split()))
li.sort(reverse=True)
ans = 0

for i in range(n//2):
    if i == 0:
        ans += li[i]
    else:
        ans += li[i]*2

if n%2 == 1:
    ans += li[i+1]

print(ans)

Solution (Python):
N=int(input())
A=list(map(int,input().split()))
A.sort(reverse=True)
kokochi=A[0]

for i in range(3,N+1):
    kokochi+=A[(i-1)//2]

print(kokochi)

Solution (Python):

def main():
  n = int(input())

  arr = sorted(map(int, input().split()), reverse=True)

  ans = arr[0]
  n -= 2

  F = [arr[0], arr[0]]
  i = 1
  while n >= 0:
    if n <= 1:
      ans += n * arr[i]
      break

    ans += 2 * arr[i]
    i += 1
    n -= 2

  print(ans)


main()

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



a.sort(reverse = True)


confort = 0
for i in range(n):
    if i == 0:
        confort += 0
    elif i == 1:
        confort += a[0]
    else:
        if i % 2 == 0:
            p = int(i/2)
            confort += a[p]
        elif i % 2 == 1:
            p = int((i-1)/2)
            confort += a[p]

print(confort)

Solution (Python):
N=int(input())
A=list(map(int, input().split()))
A=sorted(A)[::-1]
if N==1:
  print(0)
  exit()
if N==2:
  print(A[0])
  exit()
  
A.append(0)
d=A[0]
D=[]
cnt=1
for i in range(N):
  if d==A[i+1]:
    cnt+=1
  else:
    D.append((d,cnt))
    cnt=1
    d=A[i+1]
ans=0
nokori=N
for a,b in D:
  if b*2<=nokori:
    ans+=a*b*2
    nokori-=b*2
  else:
    ans+=nokori*a
    nokori=0
print(ans-A[0])

Solution (Python):
def main():
    n = int(input())
    a = list(map(int, input().split()))
    a.sort(reverse=True)
    ret = a[0]
    i = 2
    for _a in a[1:]:
        if i == n:
            break
        ret += _a
        i += 1
        if i == n:
            break
        ret += _a
        i += 1
    print(ret)




if __name__ == "__main__":
    main()

Solution (Python):
N = int(input())
a = list(map(int,input().split()))
total=0

list.sort(a, reverse=True)

if N %2== 0:
	for i in range(int(N/2)):
		if i == 0:
			total += a[i]
		else:
			total += a[i]*2
else:
	for i in range(int((N-1)/2)):
		if i == 0:
			total += a[i]
		else:
			total += a[i]*2
	total += a[int((N-1)/2 )]
print(total)

Solution (Python):
from collections import deque

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

A.sort(reverse=True)

result = [A[0]]
space = deque(result)
point = 0

for a in A[1:]:
    s = space.popleft()
    point += s
    space.append(a)
    space.append(a)
print(point)

Solution (Python):
from collections import deque

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

h.sort()
h.reverse()

en = deque()
ans = 0

for i, j in enumerate(h):
    if i == 0:
        en.append((j,j))
    else:
        maxtmp, mintmp = en.popleft()
        ans += mintmp
        en.append((maxtmp, j))
        en.append((mintmp, j))

print(ans)

Solution (Python):
















import sys
def _p(*_a):
  
  _s=" ".join(map(str,_a))
  
  sys.stderr.write(_s+"\n")

def _pa(_aa):
  
  for _a in _aa: _p(_a)

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

A.sort(reverse=True)
_p(A)

if N==1:
  print(0)
  exit()

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

if N==3:
  print(A[0]+A[1])
  exit()


from collections import deque
Q = deque()
Q.append(A[0])

ans = 0
for a in A[1:]:
  q = Q.popleft()
  ans += q
  Q.append(a)
  Q.append(a)
  

print(ans)

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

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

ans = 0

if n % 2 == 0:
    t = n // 2
    for i in range(t):
        if i == 0:
            ans += a[i]
        else:
            ans += a[i] * 2
    print(ans)
else:
    t = (n + 1) // 2
    for i in range(t):
        if i == 0:
            ans += a[i]
        elif i == t-1:
            ans += a[i]
        else:
            ans += a[i] * 2
    print(ans)

Solution (Python):

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

A.sort()

sc = 0
sc += A.pop(-1)

c=0
for i in range(10**6):
    if c>=N-2:
        break
    p=A.pop(-1)
    sc+=p
    c+=1
    if c>=N-2:
        break
    sc+=p
    c+=1
        
print(sc)

Solution (Python):


import sys
import numpy as np
int1 = lambda x: int(x) - 1
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
sys.setrecursionlimit(500000)

N, *A = map(int, read().split())

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

idx = 1
ans = A[0]
flag = False
for i in range(N - 2):
    ans += A[idx]
    if not flag:
        flag = True
        continue
    if flag:
        flag = False
        idx += 1
print(ans)

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

ans = [0]
for i in range(n):
    top = a[i]
    if i == 0:
        ans.append(top)
    elif i != n - 1:
        ans += [top] * 2

print(sum(ans[:n]))

Solution (Python):
import math
N = int(input())
num = list(map(int, input().split()))

num.sort()
num.reverse()

score = 0
index = 0.5
for i in range(N-1):
    score += num[math.floor(index)]
    index += 0.5
print(score)

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

if N == 2:
    ans = A[0]
elif N == 3:
    ans = sum(A[:2])
elif N == 4:
    ans = sum(A[:2])+A[1]
elif N == 5:
    ans = sum(A[:2])+A[1]+A[2]
elif N == 6:
    ans = sum(A[:2])+A[1]+A[2]*2
else:
    ans = sum(A[:2])+A[1]+A[2]*2
    
    ind = N-6
    if ind%2 == 0:
        ans += sum(A[3:3+ind//2])*2
    else:
        ans += sum(A[3:3+ind//2])*2+A[3+ind//2]


print(ans)

Solution (Python):
n = int(input())
a = [int(i) for i in input().split()]
ans = 0
ind = n-1
a.sort()
for i in range(n-1):
    if i%2:
        ans += a[ind]
    else:
        ans += a[ind]
        ind -= 1

print(ans)

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

ans = A[0]
d = (N-2) // 2
m = (N-2) % 2
ans += sum(A[1:1+d]) * 2
if m == 1:
  ans += A[1+d]

print(ans)

Solution (Python):
n=int(input())
a = list(map(int, input().split()))
a.sort()
if n % 2 == 0:
  result = 2*sum(a[n//2:]) - a[n-1]
else:
  result = 2*sum(a[n//2:]) - a[n-1] - a[n//2]
print(result)

Solution (Python):



import sys
sys.setrecursionlimit(10**7)
from pprint import pprint as pp
from pprint import pformat as pf



import math

import bisect

from heapq import heappush, heappop
class PriorityQueue:

    def __init__(self):
        self.contaier = []

    def push(self, priority): 
        heappush(self.contaier, (-1 * priority, priority))

    def pop(self):
        return heappop(self.contaier)[1]

    def is_empty(self):
        return len(self.contaier) == 0

def solve(data):
    confortable = 0
    chairs = PriorityQueue()
    chairs.push(data[0])
    for d in data[1:]:
        c = chairs.pop()
        confortable += c
        chairs.push(d)
        chairs.push(d)
    return confortable


if __name__ == '__main__':
    n = int(input())
    data = list(map(int, input().split()))
    data.sort()
    data.reverse()
    
    
    ans = solve(data)
    
    print(ans)

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

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

ans=l[0]
a=2

for i in range(1,n):
    ans+=(min(2,n-a))*l[i]
    a+=min(2,n-a)
    if a==n:
        break

print(ans)

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

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

print(ans)

Solution (Python):
N = int(input())
As = sorted(list(map(int, input().split())))
As.reverse()
ans = 0
for n in range(1,N):
  
  ans += As[n//2]
print(ans)

Solution (Python):
from collections import defaultdict, deque, Counter
from heapq import heappush, heappop, heapify
import bisect
import random
from itertools import permutations, accumulate, combinations, product
import sys
import string
from bisect import bisect_left, bisect_right
from math import factorial, ceil, floor, acos, asin, atan, sqrt, tan, cos, pi
from operator import mul
from functools import reduce
from pprint import pprint


sys.setrecursionlimit(10 ** 7)
INF = 10 ** 20
def LI(): return list(map(int, sys.stdin.readline().split()))
def I(): return int(sys.stdin.readline())
def LS(): return sys.stdin.readline().split()
def S(): return sys.stdin.readline().strip()
def IR(n): return [I() for i in range(n)]
def LIR(n): return [LI() for i in range(n)]
def SR(n): return [S() for i in range(n)]
def LSR(n): return [LS() for i in range(n)]
def SRL(n): return [list(S()) for i in range(n)]
def MSRL(n): return [[int(j) for j in list(S())] for i in range(n)]


mod = 10 ** 9 + 7


n = I()
A = LI()
A.sort(reverse=True)
q = [-A[0]]
ret = 0
for i in range(1, n):
    ret += -heappop(q)
    heappush(q, -A[i])
    heappush(q, -A[i])

print(ret)




ret = 0

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

A.sort(reverse=True)
cnt = 0
idx = 0
ans = []
while cnt < N:
    if idx == 0:
        ans.append(A[idx])
        cnt += 1
    else:
        ans.append(A[idx])
        ans.append(A[idx])
        cnt += 2
    idx += 1
print(sum(ans[:N-1]))

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

ans = A[0]
cnt = 1
num = 2
for i in range(N-2):
    
    ans += A[cnt]
    num += 1
    if num == N:
        break
        
    ans += A[cnt]
    num += 1
    if num == N:
        break
        
    cnt += 1
    

print(ans)

Solution (Python):
n = int(input())
x= [int(x) for x in input().split()]
x.sort(reverse=True)

c = 0
if n%2 == 0:
  t = (n-2)//2
  print(x[n//2-1] + sum(x[0:t]) + sum(x[1:t+1]))
  
    
if n%2 == 1:
  t = (n-1)//2
  print(sum(x[0:t]) + sum(x[1:t+1]))

Solution (Python):
N = int(input())
A = list(map(int, input().split()))
A.sort(reverse=True)
ANS = A[0]

for i in range(N-2):
    index = i // 2
    ANS += A[index+1]
print(ANS)

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

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

Solution (Python):
n = int(input())
A = list(map(int, input().split()))
A = sorted(A, reverse=True)

'''for i in range(n):
	if i==0:
		conf = {A[i]:1}
		ans = 0
	else:
		add=max(conf.keys())
		ans+=add
		conf[A[i]] =2
		if conf[add] >1:
			conf[add] -= 1
		else:
			conf.pop(add)'''

if n%2==0:
	print(sum(A[:n//2]) *2 -A[0])
else:
	print(sum(A[:n//2]) *2 -A[0] +A[n//2])

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

Solution (Python):
N = int(input())
l = list(map(int, input().split()))
l.sort()
l.reverse()
s = l[0]
if N%2==0:
  c = N//2-1
  for i in range(c):
    s = s + l[i+1]*2
  
else:
  d = (N-3)//2
  for i in range(d):
    s = s + l[i+1]*2
  s = s + l[(N-1)//2]
print(s)

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

a=sorted(a,reverse=True)
if n==2:
    print(max(a))
    exit(0)

ans=a[0]
a=a[1:]
from math import floor

for i in range(n-2):
    index=floor(i/2)
    ans+=a[index]

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=ans+a[i//2]
print(ans)

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