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):

import os
from sys import stdin, stdout


def solve(tc):
    n = int(stdin.readline().strip())
    seq = list(map(int, stdin.readline().split()))

    seq = sorted(seq, reverse=True)

    ans = seq[0]
    cur = 1
    shared = 0
    for i in range(2, n):
        ans += seq[cur]
        shared += 1
        if shared==2:
            cur += 1
            shared = 0
    print(ans)



tcs = 1
tc = 1
while tc <= tcs:
    solve(tc)
    tc += 1

Solution (Python):
import heapq
def main():
  N = int(input())
  A = list(map(int, input().split()))
  A.sort(reverse = True)
  member = [-1*A[0]]
  ans = 0
  for i in range(1, N):
    ans += -1*heapq.heappop(member)
    for _ in range(2):
      heapq.heappush(member, -1*A[i])
  print(ans)
  
  
    
if __name__ == "__main__":
  main()

Solution (Python):
import queue

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

A = sorted(A,reverse=True)

ans = 0
q = queue.Queue()
q.put(A[0])
for i in range(1,N):
    ans += q.get()

    q.put(A[i])
    q.put(A[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):
N = int(input())
A = list(map(int, input().split()))


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

Solution (Python):
def solve(A,N):
    A.sort(reverse = True)
    ans = A[0]
    if N % 2 == 0:
        pt = N // 2 - 1
        for i in range(1,pt+1):
            ans += (2 * A[i])
    else:
        pt = (N-1) // 2
        for i in range(1,pt):
            ans += (2 * A[i])
        ans += A[pt]
    return ans

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

    print(solve(A,N))

if __name__ == "__main__":
    main()

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):
import sys

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

n = int(input())
a_li = list(map(int, input().split()))
a_li.sort(reverse=True)
dd = int((n+1)/2)
if n%2==0:
    print(2*sum(a_li[:dd])-a_li[0])
else:
    print(2*sum(a_li[:dd])-a_li[0]-a_li[dd-1])

Solution (Python):











import sys
sys.setrecursionlimit(10 ** 5 + 10)
def input(): return sys.stdin.readline().strip()

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

        

    m=n
    m-=2
    p,q=divmod(m,2)
    if q==0:
        ans=2*sum(A[:p+1])
        ans-=A[0]
    else:
        ans=2*sum(A[:p+2])
        ans-=A[0]
        ans-=A[p+1]
    print(ans)





    
resolve()

Solution (Python):

n = int(input())
nums = sorted(map(int, input().split(" ")), reverse=True)

from collections import deque

for i in range(n):
    if i == 0:
        num0 = nums[i]
        out = 0
    elif i == 1:
        num1 = nums[i]
        out = num0
        q = deque([[num0, num1], [num0, num1]])
    else:
        in_e = q.popleft()
        
        cur = nums[i]
        out += in_e[1]
        for nn in in_e: 
            e = [nn, cur]
            q.append(e)

print(out)

Solution (Python):
if __name__ == '__main__':
    n = int(input())
    arr = list(map(int, input().split()))
    arr.sort(reverse=True)
    halfway = len(arr)//2 + 1
    otherhalf = n-halfway
    total = 0
    for i in range(1, halfway+2):
        if i == 1:
            total += arr[0]
        else:
            if i < halfway:
                total += min(arr[0], arr[i-1])
            if otherhalf >= 1:
                total += min(arr[0], arr[i-1])
                otherhalf -= 1
    print(total)

Solution (Python):
import sys, re
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, tan, asin, acos, atan, radians, degrees, log2, gcd
from itertools import accumulate, permutations, combinations, combinations_with_replacement, product, groupby
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from bisect import bisect, bisect_left, insort, insort_left
from heapq import heappush, heappop
from functools import reduce
def input(): return sys.stdin.readline().strip()
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
def ZIP(n): return zip(*(MAP() for _ in range(n)))
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
mod = 10 ** 9 + 7 

from decimal import *



N = INT()
A = LIST()

A.sort(reverse = True)

p = [A[0]]

for i in range(1, N):
	p += [A[i]]*2

print(sum(p[:N-1]))

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

m = 1
j = 0
for i in range(n-1):
    ans += a[j]
    m += 1
    if m == 2:
        m = 0
        j += 1
    
print(ans)

Solution (Python):

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

b.sort(reverse=True)
ret = 0
from collections import deque
stack_deque = deque([])
if n == 1:
    print(0)
    import sys
    sys.exit()
if n == 2:
    print(b[0])
    import sys
    sys.exit()

stack_deque.append(b[1])
stack_deque.append(b[1])
ret = b[0]
for bi in b[2::]:
    ret += stack_deque.popleft()
    stack_deque.append(bi)
    stack_deque.append(bi)
print(ret)

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

Solution (Python):
from functools import reduce
from fractions import gcd
import math
import bisect
import itertools
import sys
sys.setrecursionlimit(10**7)
input = sys.stdin.readline
INF = float("inf")



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

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


if __name__ == '__main__':
    main()

Solution (Python):
from collections import deque

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

if n == 2:
    print(max(A))
    exit()

A.sort()
B = A[::-1]
point = deque()
point.append(B[0])
ans = 0
for i in range(1, n):
    ans += point.popleft()
    point.append(B[i])
    point.append(B[i])
print(ans)

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

def int1(x): return int(x) - 1
def II(): return int(input())
def MI(): return map(int, input().split())
def MI1(): return map(int1, input().split())
def LI(): return list(map(int, input().split()))
def LI1(): return list(map(int1, input().split()))
def LLI(rows_number): return [LI() for _ in range(rows_number)]
def MS(): return input().split()
def LS(): return list(input())
def LLS(rows_number): return [LS() for _ in range(rows_number)]
def printlist(lst, k=' '): print(k.join(list(map(str, lst))))
INF = float('inf')

from collections import deque





def solve():
    N = II()
    A = LI()
    A = deque(sorted(A)[::-1])

    q = deque([A.popleft()])

    ans = 0
    while A:
        ans += q.popleft()
        a = A.popleft()
        q.extend([a, a])
    print(ans)

if __name__ == '__main__':
    solve()

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

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

A.sort(reverse=True)

gain = 0

n = 1
while n <= N-1:
  if n % 2:
    gain += A[(n-1)//2]
    
  else:
    gain += A[(n+1)//2]
    
  n += 1

print(gain)

Solution (Python):
import queue
import sys
def input():
    return sys.stdin.readline().rstrip('\n')
    

def calc(N, A):
    A.sort(key=lambda x: -x)
    q = queue.Queue()
    q.put(A[0])
    ans = 0
    for a in A[1:]:
        ans += q.get()
        q.put(a)
        q.put(a)
    return ans


N = int(input())
A = [int(s) for s in input().split()]
print(calc(N, A))

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())
F = list(map(int, input().split()))

F = sorted(F)
S = list()
for f in F:
    S.append(f)
    S.append(f)

S = S[:-1][-1::-1]
print(sum(S[:N - 1]))

Solution (Python):
import sys 
import heapq

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

A.sort(reverse=True)
q = []
heapq.heappush(q, (-A[0], (A[0], A[0])))

ans = 0
for i in range(1, N):
    v, (left, right) = heapq.heappop(q)
    
    ans += -v
    heapq.heappush(q, (-1 * min(left, A[i]), (left, A[i])))
    heapq.heappush(q, (-1 * min(right, A[i]), (right, A[i])))

print(ans)

Solution (Python):
n=int(input())
a=list((map(int,input().split())))
a.sort(reverse=True)
p=1
ans=a[0]
i=1
while p<(n-1):
    ans+=(2*a[i])
    
    i+=1
    p+=2
if p!=(n-1):
    ans-=a[i-1]
print(ans)

Solution (Python):
from collections import deque
n = int(input())
a = list(map(int,input().split()))
a.sort(reverse=True)
score = deque([a.pop(0)])

total = 0

for i in a:
    total += score.popleft()
    score.append(i)
    score.append(i)
print(total)

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

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

array = [a[0]]

i = 1
while len(array) <= n:
  array.append(a[i])
  array.append(a[i])
  i += 1
  
print(sum(array[0:n-1]))

Solution (Python):
n = int(input())
As = [int(x) for x in input().split()]
As.sort(reverse=True)
mx = As[0]
i = 1
if n%2 == 0:
    for j in range(int((n-2)/2)):
        mx += As[i]*2
        i += 1
else:
    for j in range(int((n-2)/2)):
        mx += As[i]*2
        i += 1
    mx += As[i]
print(mx)

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

a.sort(reverse=True)

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

if n % 2 == 1:
  ans += a[(n - 1) // 2]

print(ans)

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

A.sort(reverse=True)

cnt = 0
if N % 2 == 0:
    cnt += A[0]
    for i in range(1, N//2):
        cnt += A[i] * 2
    
else:
    cnt += A[0]
    for i in range(1, N//2):
        cnt += A[i] * 2
    cnt += A[i+1]
print(cnt)

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


from heapq import heapify, heappush, heappop
from collections import defaultdict as dd, deque, Counter


def data(): return sys.stdin.readline().strip()
def mdata(): return list(map(int, data().split()))
def outl(var): sys.stdout.write(' '.join(map(str, var)) + '\n')
def out(var): sys.stdout.write(str(var) + '\n')

INF = 10**9
mod = 998244353


n=int(data())
a=mdata()
a.sort(reverse=True)
ans=a[0]
ind=1
k=0
for i in range(2,n):
   ans+=a[ind]
   k+=1
   if k==2:
       k=0
       ind+=1
out(ans)

Solution (Python):
N = int(input())
A = [int(i) for i in input().split()]
A.sort(reverse=True)
point = 0
for i in range(N):
    if i == 0:
        continue
    point += A[int(i/2)]
print(point)

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

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

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

A.sort(reverse=True)

Sum = 0

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

print(Sum)

Solution (Python):
import sys


if(__name__ == "__main__"):

    N = int( input().strip() )


    list_a = list( map(int, input().strip().split()) )
    list_a.sort(reverse=True)
    comfortables = list_a[0]
    N_twos = (N-2)//2
    if(N%2 !=0):
        comfortables+= list_a[N_twos+1]
    for i in range(1, N_twos+1):
        comfortables += list_a[i] * 2
    print(comfortables)

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

Solution (Python):
def getN():
    return int(input())
def getNM():
    return map(int, input().split())
def getList():
    return list(map(int, input().split()))
def getArray(intn):
    return [int(input()) for i in range(intn)]
def input():
    return sys.stdin.readline().rstrip()
def rand_N(ran1, ran2):
    return random.randint(ran1, ran2)
def rand_List(ran1, ran2, rantime):
    return [random.randint(ran1, ran2) for i in range(rantime)]
def rand_ints_nodup(ran1, ran2, rantime):
  ns = []
  while len(ns) < rantime:
    n = random.randint(ran1, ran2)
    if not n in ns:
      ns.append(n)
  return sorted(ns)

def rand_query(ran1, ran2, rantime):
  r_query = []
  while len(r_query) < rantime:
    n_q = rand_ints_nodup(ran1, ran2, 2)
    if not n_q in r_query:
      r_query.append(n_q)
  return sorted(r_query)

from collections import defaultdict, deque, Counter
from sys import exit
from decimal import *
import heapq
import math
from fractions import gcd
import random
import string
import copy
from itertools import combinations, permutations, product
from operator import mul
from functools import reduce
from bisect import bisect_left, bisect_right

import sys
sys.setrecursionlimit(1000000000)
mod = 10 ** 9 + 7






N = getN()
A = getList()
A.sort(reverse = True)
ans = A[0]
for i in range(N - 2):
    ans += A[1 + (i // 2)]
print(ans)

Solution (Python):
import sys
import collections
ri = lambda: int(sys.stdin.readline())
rl = lambda: list(map(int, sys.stdin.readline().split()))

n = ri()
li = sorted(rl(), reverse=True)
q = collections.deque([max(li)])
score = 0
for i in li[1:]:
    a = q.popleft()
    score += a
    q.append(i)
    q.append(i)
print(score)

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

A.sort()
ans = 0

if N <= 3:
  print(sum(A[1:]))
else:
  for i in range(1, N):
    i //= 2
    ans += A[-1-i]
  print(ans)

Solution (Python):

MOD = 10 ** 9 + 7
INFI = 10**10

import math
from collections import deque
import itertools
import heapq

from fractions import Fraction
import copy
from functools import lru_cache
from collections import defaultdict
import pprint




def sosuhante(n):
    for k in range(2, int(math.sqrt(n))+1):
        if n% k ==0:
            return False
    return True
def cmb(n, r):
    if n - r < r: r = n - r
    if r == 0: return 1
    if r == 1: return n

    numerator = [n - r + k + 1 for k in range(r)]
    denominator = [k + 1 for k in range(r)]

    for p in range(2,r+1):
        pivot = denominator[p - 1]
        if pivot > 1:
            offset = (n - r) % p
            for k in range(p-1,r,p):
                numerator[k - offset] /= pivot
                denominator[k] /= pivot

    result = 1
    for k in range(r):
        if numerator[k] > 1:
            result *= int(numerator[k])

    return result

def kingaku(a,b,n):
    keta=len(str(n))
    return a*n+b*keta

def my_index(l, x, default=False):
    if x in l:
        return l.index(x)
    else:
        return default




def ret(a):
    c=[None]*(len(a)-1)
    if len(a)==1:
        return a[0]
    elif len(a)==0:
        return 0
    for i in range(1,len(a)):
        c[i-1]=abs(a[i]-a[i-1])
    return ret(c)

def soinsubunkai(n):
    a = []
    i = 1
    while i*i <= n:
        if n % i == 0 and i!=1:
            a.append(i)
            n=n//i

        if n% i !=0 or i==1:
            i += 1
    nokori=[n]
    return a + nokori

def make_divisors(n):
    lower_divisors , upper_divisors = [], []
    i = 1
    while i*i <= n:
        if n % i == 0:
            lower_divisors.append(i)
            if i != n // i:
                upper_divisors.append(n//i)
        i += 1
    return lower_divisors + upper_divisors[::-1]

def main():
    n=int(input())
    a=list(map(int,input().split()))
    a=sorted(a,reverse=True)
    if n%2==0:
        a1=a[0:n//2]
        a2=a[n//2:]
    else:
        a1=a[0:n//2+1]
        a2=a[n//2+1:]

    count=0
    if n>=3:
        for i in range(len(a1)):
            count+=a1[i]
        for i in range(1,len(a2)):
            count+=a1[i]
    else:
        count=a[0]
    print(count)

if __name__ == "__main__":

    main()

Solution (Python):
from sys import stdin
nii=lambda:map(int,stdin.readline().split())
lnii=lambda:list(map(int,stdin.readline().split()))

n=int(input())
a=lnii()
a.sort(reverse=True)

ans=a[0]

inx=1
i=2
while i<n:
  ans+=a[inx]

  if i%2==1:
    inx+=1

  i+=1

print(ans)

Solution (Python):
import sys
import math
import collections
import decimal
import itertools
from collections import deque
from functools import reduce
import heapq
import copy
n = int(input())


a = list(map(int, sys.stdin.readline().split()))

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

print(p)

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

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

t.sort(reverse=True)

ans = t[0]

i = 1

count = 1

flag = False

while count < n-1:
    ans += t[i]
    if flag:
        flag = False
        i += 1
    else:
        flag = True
    count += 1
print(ans)

Solution (Python):
n,*l=map(int,open(0).read().split())
from heapq import *
l.sort()
hq=[-l.pop()]
heapify(hq)
a=0
for _ in range(n-1):
  m=heappop(hq)
  a-=m
  t=-l.pop()
  heappush(hq,t)
  heappush(hq,t)
print(a)

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

A.sort()
ans = 0
ans += A.pop()
i = 1
now =0
while i < N-1:
    now = A.pop()
    ans += now*2
    i += 2
if i > N-1:
    ans -= now
print(ans)

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

a.sort(reverse=True)

n -= 1

idx = 0
score = a[idx]
n -= 1
idx += 1

while n > 0:
    if n > 1:
        score += a[idx] * 2
        n -= 2
        idx += 1
    else:
        score += a[idx]
        n -= 1

print(score)

Solution (Python):
from collections import deque

n = int(input())
a = list(map(int, input().split()))
a.sort(reverse=True)
a = deque(a)
ans = a[0]
a.popleft()
n-=2
while n>0:
    if n>=2:
        ans += a[0]*2
        n-=2
        a.popleft()
    else:
        ans += a[0]
        n-=1
print(ans)

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

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

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

a.sort(reverse=True)
stack = list()
stack.append(a[0])

if n == 2:
    print(stack[0])
    exit(0)

for i in range((len(a) // 2) + 1):
    stack.append(a[i + 1])
    stack.append(a[i + 1])

print(sum(stack[:n-1]))

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

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

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

Solution (Python):

import sys


def solve(N: int, A: "List[int]"):
    A = sorted(A, reverse=True)
    if N==2:
        print(A[0])
        return

    i = 0
    while(pow(2,i)<N): i+=1
    

    rem = N-2**(i-1)
    if rem%2 == 1: od = 1
    else: od = 0
    
    ans = sum(A[:2**(i-2)])*2 - A[0]
    
    
    ans+= sum(A[2**(i-2):2**(i-2)+rem//2])*2
    

    if od:
        ans+= A[2**(i-2)+rem//2]
    print(ans)

    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(reverse=True)
s = 0
if n % 2 == 0:
    s += a[0]
    for i in range((n - 2) // 2):
        s += a[i + 1] * 2
else:
    s += a[0]
    for i in range((n - 3) // 2):
        s += a[i + 1] * 2
    s += a[(n - 3) // 2 + 1]
print(s)

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

a.sort(reverse=True)
ans+=int(a[0])
n-=2
where=1
kaisu=0
while n>0:
  ans+=int(a[where])
  kaisu+=1
  n-=1
  if kaisu==2:
    kaisu=0
    where+=1

print(str(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):
n=int(input())
a=list(map(int,input().split()))
a.sort()
m=a[-1]
del a[-1]
if n%2==0:
  for _ in range(n//2-1):
    m+=2*a.pop(-1)
  print(m)  
else:
  for _ in range((n-3)//2):
    m+=2*a.pop(-1)
  m+=a[-1]
  print(m)

Solution (Python):



def compute_max(n, bs):
    cs = sorted(bs, reverse=True)
    if n == 1:
        return 0
    else:
        coefficients = [0 for _ in range(n)]
        coefficients[0] = 1
        d, m = divmod(n - 2, 2)
        for i in range(1, d + 1):
            coefficients[i] = 2
        coefficients[d + 1] = m
        res = sum(c * d for c, d in zip(cs, coefficients))
        return res


def main():
    n = int(input())
    bs = [int(b) for b in input().split()]
    res = compute_max(n, bs)
    print(res)


if __name__ == '__main__':
    main()

Solution (Python):
N = int(input())
l = [int(x) for x in input().split()]
l.sort(reverse = True)
ans = 0
for i in range(N-1):
    ans += l[(i+1)//2]
print(ans)

Solution (Python):


import copy
import random
import bisect 
import fractions 
import math
import sys
import collections
from decimal import Decimal 

mod = 10**9+7
sys.setrecursionlimit(mod) 

d = collections.deque()
def LI(): return list(map(int, sys.stdin.readline().split()))

N = int(input())
A = LI()

A.sort(reverse=1)
ans = 0
ans += A[0]

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

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

Solution (Python):
N = int(input())
a = input().split()
a = list(map(int,a))
sa = sorted(a,reverse=True)
count = 0
count += sa[0]
f = 0
t = 1
for _ in range(N-2):
    if f == 2:
        t += 1
        count += sa[t]
        f = 0
    else:
        count += sa[t]
    f += 1
print(count)

Solution (Python):

from __future__ import division, print_function

import os
import 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 main():
    n = int(input())
    a = sorted([int(ai) for ai in input().split()], reverse=True)

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

    print(sol)




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):
import heapq
FAST_IO = 1
if FAST_IO:
    import io, sys, atexit
    rr = iter(sys.stdin.read().splitlines()).next
    sys.stdout = _OUTPUT_BUFFER = io.BytesIO()

    @atexit.register
    def write():
        sys.__stdout__.write(_OUTPUT_BUFFER.getvalue())
else:
    rr = raw_input
rri = lambda: int(rr())
rrm = lambda: map(int, rr().split())
rrmm = lambda n: [rrm() for _ in xrange(n)]

rrn = lambda n: [ rr() for _ in xrange(n)]

N = rri()
arr = rrm()
arr = sorted(arr)
def solve(N, arr):
    pq = []
    cur1 = arr.pop()
    ans = cur1
    cur2 = arr.pop()
    heapq.heappush(pq, (-cur2, (cur2, cur1)))
    heapq.heappush(pq, (-cur2,(cur1, cur2)))
    while arr:
        neg_max, (start, end) = heapq.heappop(pq)
        ans-=neg_max
        cur = arr.pop()
        heapq.heappush(pq, (-cur, (start, cur)))
        heapq.heappush(pq, (-cur, (cur, end)))
    return ans
print(solve(N, arr))

Solution (Python):
n = int(input())
l = list(map(int, input().split()))
cnt = 2
l.sort(reverse = True)
ans = l[0]
for i in l[1: ]:
    if cnt == n: break
    ans += i
    cnt -= -1
    if cnt == n: break
    ans += i
    cnt -= -1
print(ans)

Solution (Python):


import sys
import pprint
from collections import deque


sys.setrecursionlimit(10 ** 6)

class Logger:
	def __init__(self, debug):
		self.debug = debug
	def print(self, *args):
		if self.debug:
			pprint.pprint(args)


def main():
	log = Logger(0)
	n = int(sys.stdin.readline())
	a = list(map(int, sys.stdin.readline().split()))
	a = deque(sorted(a))
	if len(a) == 2:
		print(max(a))
		exit()
	if len(a) == 3:
		print(a[-1] + a[-2])
		exit()
	ans = 0
	a1 = a.pop()
	a2 = a.pop()
	a3 = a.pop()
	que = deque([[a1, a2], [a2, a3], [a3, a1]])
	ans += a1 + a2
	while len(a) != 0:
		log.print(que, ans)
		between = que.popleft()
		insert = a.pop()
		ans += min(between)
		que.append([between[0], insert])
		que.append([insert, between[1]])
	print(ans)




main()

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

A.sort(reverse=True)

ans = A[0]

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

print(ans)

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

ans = a[0]
idx = 1
n -= 2
while n > 0:
    if n == 1:
        ans += a[idx]
        n -= 1
    else:
        ans += 2*a[idx]
        n -= 2
    idx += 1
print(ans)

Solution (Python):
import sys

def IS(): return sys.stdin.readline().rstrip()
def II(): return int(IS())
def MII(): return list(map(int, IS().split()))
def MIIZ(): return list(map(lambda x: x-1, MII()))
from collections import deque

def main():
    n = II()
    aa = MII()
    aa.sort(reverse=True)
    dq = deque(aa)
    dq_p = deque()

    total = 0
    total += dq.popleft()
    next_point = dq.popleft()
    dq_p.append(next_point)
    dq_p.append(next_point)

    while dq:
        d = dq.popleft()
        dq_p.append(d)
        dq_p.append(d)
        total += dq_p.popleft()
    print(total)


if __name__ == '__main__':
    main()

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

Solution (Python):
import heapq
N = int(input())
A = list(map(int,input().split()))
heap = []
for i in range(N):
    heapq.heappush(heap,-A[i])
if N==2:
    ans = -heapq.heappop(heap)
elif N==3:
    ans = -heapq.heappop(heap)-heapq.heappop(heap)
else:
    ans = 0
    ans = -heapq.heappop(heap)
    if N%2==0:
        for _ in range((N-2)//2):
            a = -heapq.heappop(heap)
            ans += 2*a
    else:
        for _ in range((N-3)//2):
            a = -heapq.heappop(heap)
            ans += 2*a
        a = -heapq.heappop(heap)
        ans += a
print(ans)

Solution (Python):
n = int(input())
A = [int(x) for x in input().split()]
A.sort(reverse=True)
print(A[0] + sum(A[1:(n - 2) // 2 + 1]) * 2 +
      (0 if n % 2 == 0 else A[(n - 1) // 2]))

Solution (Python):
import sys


def main():
    N = int(sys.stdin.readline().rstrip())
    A = [int(x) for x in sys.stdin.readline().rstrip().split()]

    A.sort(reverse=True)

    B = []
    for j in range(N // 2 + 1):
        B.append(A[j])
        B.append(A[j])

    
    B[0] = 0

    print(sum(B[:N]))


main()

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

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

print(ans)

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

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

a_list.sort()
a_list=a_list[::-1]

sumn=0
if N%2==0:
    sumn+=a_list[0]
    sumn+=2*sum(a_list[1:N//2])
else:
    sumn+=a_list[0]
    sumn+=2*sum(a_list[1:N//2])
    sumn+=a_list[N//2]

print(sumn)