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)
ans = a[0]

tmp = n-2

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

Solution (Python):
import sys
from collections import defaultdict
readline = sys.stdin.buffer.readline
sys.setrecursionlimit(10**8)


def geta(fn=lambda s: s.decode()):
    return map(fn, readline().split())


def gete(fn=lambda s: s.decode()):
    return fn(readline().rstrip())


def main():
    n = gete(int)
    a = list(geta(int))

    a.sort(reverse=True)

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

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

    print(ans)


if __name__ == "__main__":
    main()

Solution (Python):
N = int(input())
a = list(map(int, input().split()))
a.sort(reverse=True)
total = a[0]
index = 1
cnt = 0
for i in range(N - 2):
    if cnt == 2:
        index += 1
        cnt = 0
    total += a[index]
    cnt += 1

print(total)

Solution (Python):
n=int(input())
ls=list(map(int,input().split()))
ls.sort(reverse=True)
ans=ls[0]
pls=[ls.pop(0),ls.pop(0)]
cnt=0
scnt=0

for i in ls:
  pls.append(i)
  ans+=pls[cnt+1]
  if scnt==0:
    scnt=1
  else:
    scnt=0
    cnt+=1
print(ans)

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

Solution (Python):
import sys

sys.setrecursionlimit(10**7)
def I(): return int(sys.stdin.readline().rstrip())
def LI(): return list(map(int,sys.stdin.readline().rstrip().split()))  
def LI2(): return list(map(int,sys.stdin.readline().rstrip()))  
def S(): return sys.stdin.readline().rstrip()
def LS(): return list(sys.stdin.readline().rstrip().split())  
def LS2(): return list(sys.stdin.readline().rstrip())  

N = I()
A = LI()

A = sorted(A,reverse=True)

a = (N-1)//2

b = 0
for i in range(a+1):
    b += A[i]


if N % 2 == 1:
    print(2*b-A[0]-A[a])
else:
    print(2*b-A[0])

Solution (Python):

import sys;input = sys.stdin.readline
inp,ip = lambda :int(input()),lambda :[int(w) for w in input().split()]

n = inp()
x = ip()
if n < 3:
    print(max(x))
    exit()
x.sort(reverse=True)
k = n - 2
ans = x[0]
x.pop(0)
ans += 2*sum(x[:k//2])
if k%2:
    ans += x[k//2]
print(ans)

Solution (Python):
import sys

N=int(sys.stdin.readline())

A=[int(i) for i in sys.stdin.readline().split()]

A.sort(reverse=True)

ans=0
ctr=0
i=0

while(ctr<N-1):
	if(i==0):
		ans+=A[i]
		i+=1
		ctr+=1
	else:
		ans+=A[i]
		ctr+=1
		if(ctr<N-1):
			ans+=A[i]
			ctr+=1
			i+=1

print(ans)

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

A.sort(reverse=True)


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

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

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

def list2d(a, b, c): return [[c] * b for i in range(a)]
def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)]
def list4d(a, b, c, d, e): return [[[[e] * d for j in range(c)] for j in range(b)] for i in range(a)]
def ceil(x, y=1): return int(-(-x // y))
def Yes(): print('Yes')
def No(): print('No')
def YES(): print('YES')
def NO(): print('NO')
INF = 10 ** 18
MOD = 10**9+7

from math import sqrt, floor

Ri = lambda : [int(x) for x in sys.stdin.readline().split()]
ri = lambda : sys.stdin.readline().strip()


n = int(ri())
a = Ri()
a.sort(reverse = True)

curp = 1
summ =a[0]

cur = 2
flag = True
while cur < n:
    summ+=a[curp]
    cur+=1
    if flag :
        flag = not flag
    else:
        curp+=1
        flag = True

print(summ)

Solution (Python):
from math import ceil,floor,comb,factorial,gcd,pow,sqrt,log2,cos,sin,tan,pi,inf
from itertools import accumulate,permutations,combinations,product,combinations_with_replacement
from collections import deque,defaultdict,Counter
from bisect import bisect_left,bisect_right
from operator import itemgetter
from heapq import heappop,heappush
from copy import deepcopy
from time import time
import string
import sys
sys.setrecursionlimit(10 ** 7)
def input() : return sys.stdin.readline().strip()
def INT()   : return int(input())
def MAP()   : return map(int,input().split())
def LIST()  : return list(MAP())

n = INT()
a = sorted(LIST(), reverse=True)

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

print(ans)

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


if __name__ == '__main__':
    resolve()

Solution (Python):


import re
import math
from collections import defaultdict,deque,Counter
from fractions import Fraction
import bisect
import itertools
from itertools import accumulate
from copy import deepcopy
import heapq
import random
import time
import os
import sys
from functools import lru_cache,reduce
readline=sys.stdin.readline
sys.setrecursionlimit(100000)
alp="abcdefghijklmnopqrstuvwxyz"
numbers="0123456789"
mod=int(10**9+7)
inf=int(10**19)
class Set():
    def __init__(self,A=[]):
        self.heap=[]
        self.dic=defaultdict(bool)
        self.size=0
        for a in A:self.add(a)
    
    def __str__(self):
        return str(self.heap)
    
    def add(self,x):
        if not self.find(x):
            heapq.heappush(self.heap,x)
            self.dic[x]=True
            self.size+=1

    def remove(self,x):
        if self.find(x):
            self.dic[x]=False
            self.size-=1

    def find(self,x):
        return self.dic[x]
    
    def top(self):
        while self.heap and self.dic[self.heap[0]]==False:
            heapq.heappop(self.heap)
        if self.heap:return self.heap[0]
        else:return None

    def pop(self):
        ret=None
        if self.heap:
            ret=self.top()
            self.remove(ret)
        return ret
class multiset():
    def __init__(self,A=[]):
        self.heap=[]
        self.dic=defaultdict(int)
        self.size=0
        for a in A:self.add(a)
    
    def __str__(self):
        return str(self.heap)
    
    def add(self,x):
        heapq.heappush(self.heap,x)
        self.dic[x]+=1
        self.size+=1

    def remove(self,x):
        if self.dic[x]>0:
            self.dic[x]-=1
            self.size-=1
    
    def count(self,x):
        return self.dic[x]

    def find(self,x):
        return self.dic[x]>0
    
    def top(self):
        while self.heap and self.dic[self.heap[0]]==0:
            heapq.heappop(self.heap)
        if self.heap:return self.heap[0]
        else:return None

    def pop(self):
        ret=None
        if self.heap:
            ret=self.top()
            self.remove(ret)
        return ret
class Edge():
    def __init__(self,x,y,val=1):
        self.x=x
        self.y=y
        self.val=val
class unionfind():
    def __init__(self,n):
        self.n=n
        self.P=[a for a in range(n)]
        self.rank=[0]*n
 
    def find(self,x):
        if(x!=self.P[x]):
            self.P[x]=self.find(self.P[x])
        return self.P[x]
 
    def same(self,x,y):
        return self.find(x)==self.find(y)
 
    def link(self,x,y):
        if self.rank[x]<self.rank[y]:
            self.P[x]=y
        elif self.rank[y]<self.rank[x]:
            self.P[y]=x
        else:
            self.P[x]=y
            self.rank[y]+=1
 
    def unite(self,x,y):
        self.link(self.find(x),self.find(y))
 
    def size(self):
        S=set()
        for a in range(self.n):
            S.add(self.find(a))
        return len(S)
def yn(b):print("yes" if b else "no")
def Yn(b):print("Yes" if b else "No")
def YN(b):print("YES" if b else "NO")
def ispow(a,b):
    now=b
    while now<a:
        now*=b
    return now==a
def getbin(num,size):
    A=[0]*size
    for a in range(size):
        if (num>>(size-a-1))&1==1:
            A[a]=1
        else:
            A[a]=0
    return A
def getfacs(n,mod_=0):
    A=[1]*(n+1)
    for a in range(2,len(A)):
        A[a]=A[a-1]*a
        if(mod_>0):A[a]%=mod_
    return A
def comb(n,r,mod,fac):
    if(n-r<0):return 0
    return (fac[n]*pow(fac[n-r],mod-2,mod)*pow(fac[r],mod-2,mod))%mod
def nextcomb(num,size):
    x=num&(-num)
    y=num+x
    z=num&(~y)
    z//=x
    z=z>>1
    num=(y|z)
    if(num>=(1<<size)):return False
    else:return num
def getprimes(n):
    if n==0:return []
    A=[True]*(n+1)
    A[0]=False
    A[1]=False
    for a in range(2,n+1):
        if A[a]:
            for b in range(a*2,n+1,a):
                A[b]=False
    ret=[]
    for a in range(n+1):
        if(A[a]):ret.append(a)
    return ret
def isprime(num):
    if(num<=1):return False
    i=2
    while i*i<=num:
       if(num%i==0):return False
       i+=1
    return True
def ifelse(b,t,f):return t if b else f
def factorize(n):
    b = 2
    ret=defaultdict(int)
    while b * b <= n:
        while n % b == 0:
            n //= b
            ret[b]+=1
        b+=1
    if n > 1:ret[n]+=1
    return ret
def inputintlist(row=1): 
    if row==1:
        ret=list(map(int,input().split()))
    else:
        ret=[None]*row
        for a in range(row):
            ret[a]=int(input())
    return ret
def inputfloatlist(row=1): 
    if row==1:
        ret=list(map(float,input().split()))
    else:
        ret=[None]*row
        for a in range(row):
            ret[a]=float(input())
    return ret
def istanchouzouka(A):
    f=True
    prev=min(A)-1
    for a in A:
        if prev>=a:
            f=False
        prev=a
    return f
def istanchouhigensyou(A):
    f=True
    prev=min(A)-1
    for a in A:
        if prev>a:
            f=False
        prev=a
    return f
def getallsum(A):
    s=sum(A)
    dp=defaultdict(int)
    dp[0]=1
    for a in range(0,len(A)):
        for b in range(s,-1,-1):
            if b-A[a]>=0:
                dp[b]+=dp[b-A[a]]
    return dp
def yuukoutomukou(edges):
    ret=deepcopy(edges)
    for edge in edges:
        if not edge.x==edge.y:
            ret.append(Edge(edge.y,edge.x,edge.val))
    return ret
def dijkstra(edges,V,start):
    mincost=[inf]*V
    G=[[] for a in range(V)]
    for edge in edges:
        G[edge.x].append([edge.val,edge.y])
    Q=PriorityQueue()
    Q.put([0,start])
    while not Q.empty():
        nowcost,nowx=Q.get()
        if mincost[nowx]==inf:
            mincost[nowx]=nowcost
            for cost,y in G[nowx]:
                newcost=nowcost+cost
                Q.put([newcost,y])
    return mincost
def warshallfloyd(edges,V):
    mincost=[[inf for b in range(V)] for a in range(V)]
    for a in range(V):mincost[a][a]=0
    for edge in edges:
        mincost[edge.x][edge.y]=min(mincost[edge.x][edge.y],edge.val)
    for k in range(V):
        for s in range(V):
            for t in range(V):
                if mincost[s][k]==inf or mincost[k][t]==inf:continue
                mincost[s][t]=min(mincost[s][t],mincost[s][k]+mincost[k][t])
    return mincost
def bellemanford(edges,V,start):
    mincost=[inf]*V
    mincost[start]=0
    for _ in range(V):
        for edge in edges:
            if mincost[edge.x]==inf:continue
            mincost[edge.y]=min(mincost[edge.y],mincost[edge.x]+edge.val)
    return mincost
def getmd(x1,y1,x2,y2):return abs(x1-x2)+abs(y1-y2)
def geted(x1,y1,x2,y2):return math.sqrt((x1-x2)**2+(y1-y2)**2)
class fordfulkerson():
    def __init__(self,edges,V,s,t):
        self.V=V
        self.used=[False]*V
        self.G=[[] for a in range(V)]
        self.s=s
        self.t=t
        for edge in edges:
            self.G[edge.x].append({"x":edge.x,"y":edge.y,"cap":edge.val,"rev":len(self.G[edge.y])})
            self.G[edge.y].append({"x":edge.y,"y":edge.x,"cap":0,"rev":len(self.G[edge.x])-1})
    def dfs(self,v,t,f=inf):
        if v==t:return f
        self.used[v]=True
        for a in range(len(self.G[v])):
            x=self.G[v][a]["x"]
            y=self.G[v][a]["y"]
            cap=self.G[v][a]["cap"]
            rev=self.G[y][self.G[x][a]["rev"]]
            if self.used[y] or cap==0:continue
            f2=self.dfs(y,t,min(f,cap))
            if f2>0:
                self.G[v][a]["cap"]-=f2
                rev["cap"]+=f2
                return f2
        return 0
    def maxflow(self):
        flow=0
        while True:
            self.used=[False]*V
            zouka=self.dfs(self.s,self.t)
            if zouka==0:break
            flow+=zouka
        return flow
def zipsort(*args):
    ziplist=sorted(zip(*args))
    for a in range(len(args)):
        for b in range(len(ziplist)):
            args[a][b]=ziplist[b][a]
def zipreverse(*args):
    ziplist=list(zip(*args))
    rev=[]
    for a in range(len(ziplist)-1,-1,-1):
        rev.append(ziplist[a])
    for a in range(len(args)):
        for b in range(len(rev)):
            args[a][b]=rev[b][a]


n=int(input())
A=inputintlist()
A.sort()
A.reverse()
S=[]
S.append([A[1],A[0]])
S.append([A[1],A[0]])
si=0
ans=A[0]
for a in range(2,n):
    m,M=S[si]
    S.append([A[a],M])
    S.append([A[a],m])
    ans+=m
    si+=1
print(ans)

Solution (Python):
import sys


N = int(input())

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

B = sorted(A,reverse=True)
ans = B[0]
cnt = 1

for i in range(1,N-1):
    ans += B[cnt]
    

    if i%2 == 0:
        cnt += 1
    

print(ans)

Solution (Python):
N = int(input())
A = [int(i) for i in input().split()]
A.sort(reverse=True)
ans = A[0]
cur = A[1]
num = 1
for i in range(N-2):
    if i%2 == 0:
        ans += A[num]
    else:
        ans += A[num]
        num += 1
print(ans)

Solution (Python):
n=int(input())
l=sorted(list(map(int,input().split())),reverse=1)
from heapq import heapify, heappop, heappush
h=[-l[0]]

ans=0
for i in range(1,n):
    p=-heappop(h)
    ans+=p
    heappush(h,-l[i])
    heappush(h,-l[i])
print(ans)

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

a.sort(reverse=True)
ans=a[0]+(sum(a[1:(n//2)])*2)
if n%2!=0:
    ans+=a[n//2]

print(ans)

Solution (Python):
from collections import deque

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

A.sort(reverse=True)
X=deque([A[0]])

K=0
for b in A[1:]:
    a=X.popleft()
    K+=a
    X.append(b)
    X.append(b)

print(K)

Solution (Python):
n = int(input())
a = list(map(int,input().split()))
a.sort(reverse=True)
res = a[0]
a.pop(0)

num = (n - 2) // 2
num1 = (n - 2) % 2
res += sum(a[:num]) * 2 + a[num] * num1
print(res)

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

now = a[0]
i = 0
while i+2 < n:
    now += a[i//2 + 1]
    i+=1
print(now)

Solution (Python):
import sys

read = sys.stdin.read
readline = sys.stdin.readline
readlines = sys.stdin.readlines
sys.setrecursionlimit(10 ** 9)
INF = 1 << 60
MOD = 1000000007


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

    A.sort(reverse=True)
    
    m = (N+1) // 2
    
    ans = sum(A[:m]) + sum(A[1:N-m])
    print(ans)
    return


if __name__ == '__main__':
    main()

Solution (Python):
import math
n=int(input())
a=input()
al=[int(i) for i in a.split()]
al.sort(reverse=True)
ans=al[0]
for i in range(math.floor((n-2)/2)):
    ans+=al[i+1]*2
if round((n-2)/2)-(n-2)/2!=0:
    ans+=al[math.floor((n-2)/2)+1]
print(ans)

Solution (Python):
from heapq import *

N,*A = map(int, open(0).read().split())
ai = [x * (-1) for x in A]
heapify(ai)
ans = heappop(ai) * (-1)
searching = 1
for i in range(N-2):
    if i % 2 == 0:
        temp = heappop(ai) * (-1)
    ans += temp
print(ans)

Solution (Python):
from queue import deque

class LinkedListNode:
	def __init__(self, value):
		self.value = value
		self.left = self
		self.right = self

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

A_list.sort()

circle = LinkedListNode(A_list.pop())
not_used = deque((circle, ))

total = 0
while len(A_list) > 0:
	value = A_list.pop()
	
	new_node = LinkedListNode(value)
	while True:
		head = not_used[0]
		if head.left.value >= head.value:

			total += head.value
			new_node.right = head
			new_node.left = head.left
			head.left.right = new_node
			head.left = new_node
			break
		elif head.right.value >= head.value:

			total += head.value
			new_node.right = head.right
			new_node.left = head
			head.right.left = new_node
			head.right = new_node
			break
		not_used.popleft()
	not_used.append(new_node)

print(total)

Solution (Python):


import math; from collections import *
import sys; from functools import reduce


def get_ints(): return map(int, input().strip().split())
def get_list(): return list(get_ints())
def get_string(): return list(input().strip().split())
def printxsp(*args): return print(*args, end="")
def printsp(*args): return print(*args, end=" ")

UGLYMOD = int(1e9)+7; SEXYMOD = 998244353; MAXN = int(1e5)




n = int(input())
li = sorted(get_list(), reverse = True)

ans = li[0]
pos = 1
enter = 2
while enter < n:
    ans += li[pos]*2
    enter += 2
    pos += 1
    
if enter == n + 1:
    ans -= li[pos-1]
print(ans)


'''
>>> COMMENT THE STDIN!! CHANGE ONLINE JUDGE !!
THE LOGIC AND APPROACH IS MINE @luctivud ( UDIT GUPTA )
Link may be copy-pasted here if it's taken from other source.
DO NOT PLAGIARISE.
>>> COMMENT THE STDIN!! CHANGE ONLINE JUDGE !!
'''

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

Solution (Python):
from collections import deque

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

A.sort(reverse=True)
ans = 0
Q = deque()
Q.append(A[0])
for a in A[1:]:
    b = Q[0]
    if a == b:
        Q.append(a)
        ans += b
    else:
        b = Q.popleft()
        ans += b
        Q.append(a)
        Q.append(a)
print(ans)

Solution (Python):

import sys,io,os,time
from collections import defaultdict
from collections import OrderedDict
from collections import deque
from itertools import combinations
from itertools import permutations
import bisect,math,heapq
alphabet = "abcdefghijklmnopqrstuvwxyz"

input = sys.stdin.readline


n = int(input())
arr = list(map(int , input().split()))
arr.sort(reverse = True)
ptr = 1
s = arr[0]
n-=2
while n:
	s+=arr[ptr]
	n-=1
	if n == 0: break
	s+=arr[ptr]
	n-=1
	ptr+=1
print(s)

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

A.sort(reverse=True)

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

if n%2==1:
    ans += A[n//2]

print(ans)

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

result = a[0]
n -= 2

i = 1

while n > 0:
	result += a[i]
	n -= 1
	if n > 0:
		result += a[i]
		n -= 1

	i += 1

print(result)

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

Solution (Python):
from heapq import heappush, heappop,heapify
n = int(input())
a = list(map(int,input().split()))
a.sort(reverse=True)
x = []
s = 0
s += a[0]
heappush(x,-a[1])
heappush(x,-a[1])
for i in range(2,n):
  y = heappop(x)
  s -= y
  heappush(x,-a[i])
  heappush(x,-a[i])
print(s)

Solution (Python):
from heapq import heapify, heappop, heappush
N,*A=map(int, open(0).read().split())
A=sorted(A, reverse=True)
L=[0]*N
R=[0]*N
ans=0
L[0]=0
R[0]=0
H=[(-A[0],0,0)]
heapify(H)
for i in range(1,N):
    a=A[i]
    p,pl,pr=heappop(H)
    ans+=-p
    L[pr]=i
    R[pl]=i
    L[i]=pl
    R[i]=pr
    heappush(H,(-min(A[pl],a),pl,i))
    heappush(H,(-min(A[pr],a),i,pr))
print(ans)

Solution (Python):
import sys
sys.setrecursionlimit(1000000000)
import math
from math import gcd
def lcm(a, b): return a * b // gcd(a, b)
from itertools import count, permutations, chain, product
from functools import lru_cache
from collections import deque, defaultdict
from pprint import pprint
ii = lambda: int(input())
mis = lambda: map(int, input().split())
lmis = lambda: list(mis())
INF = float('inf')
N1097 = 10**9 + 7

def meg(f, ok, ng):
    while abs(ok-ng)>1:
        mid = (ok+ng)//2
        if f(mid):
            ok=mid
        else:
            ng=mid
    return ok

def get_inv(n, modp):
    return pow(n, modp-2, modp)

def factorials_list(n, modp):    
    fs = [1]
    for i in range(1, n+1):
        fs.append(fs[-1] * i % modp)
    return fs

def invs_list(n, fs, modp):     
    invs = [get_inv(fs[-1], modp)]
    for i in range(n, 1-1, -1):
        invs.append(invs[-1] * i % modp)
    invs.reverse()
    return invs

def comb(n, k, modp):
    num = 1
    for i in range(n, n-k, -1):
        num = num * i % modp
    den = 1
    for i in range(2, k+1):
        den = den * i % modp
    return num * get_inv(den, modp) % modp

def comb_from_list(n, k, modp, fs, invs):   
    return fs[n] * invs[n-k] * invs[k] % modp



class UnionFindEx:
    def __init__(self, size):
        
        self.roots = [-1] * size
    def getRootID(self, i):
        r = self.roots[i]
        if r < 0:   
            return i
        else:
            r = self.getRootID(r)
            self.roots[i] = r
            return r
    def getGroupSize(self, i):
        return -self.roots[self.getRootID(i)]
    def connect(self, i, j):
        r1, r2 = self.getRootID(i), self.getRootID(j)
        if r1 == r2:
            return False
        if self.getGroupSize(r1) < self.getGroupSize(r2):
            r1, r2 = r2, r1
        self.roots[r1] += self.roots[r2]    
        self.roots[r2] = r1
        return True

Yes = 'Yes'
No = 'No'


def main():
    N=ii()
    A=lmis()
    A.sort()
    q = deque()
    q.append(A.pop())
    ans = 0
    while A:
        s = q.popleft()
        ans += s
        ns = A.pop()
        q.append(ns)
        q.append(ns)
    print(ans)









main()

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

print(S)

Solution (Python):
import sys
n=int(input())
a=list(map(int,input().split()))
def nibai(n):
  return n*2
a.sort(reverse=True)
sc=a[0]
if n==2:
  print(sc)
  sys.exit() 
a=a[1:]
b=list(map(nibai,a))
sc+=sum(b[:(n//2)-1])
if n%2==0:
  print(sc)
else:
  print(sc+a[(n//2)-1])

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

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

a.sort()
a.reverse()

ret = 0
ret += a[0]

for i in range(1, len(a)):
    tmp = a[i]
    if i * 2 < len(a):
        ret += tmp
    if i * 2 + 1 < len(a):
        ret += tmp

print(ret)

Solution (Python):
N = int(input())
A = sorted([int(_) for _ in input().split()], reverse=1)


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

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

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

Solution (Python):

N = int(input())

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

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

print(ans)

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

Solution (Python):
from heapq import heappop, heappush, heapify

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

q = [-a[0]]
ans = 0

for i in range(1, n):
    x = -heappop(q)
    ans += x
    heappush(q, -a[i])
    heappush(q, -a[i])

print(ans)

Solution (Python):
n = int(input())
a = [int(i) for i in input().split()]
a.sort(reverse = True)
b = [0,a[0]]
for i in range(1,n):
  b.append(a[i])
  b.append(a[i])
print(sum(b[:n]))