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):
def main(sample_file = ''):

    """ convenient functions
    
    
    
    
    
    """

    """convenient decorator
    
    
        
        
        
        
        
        
        
        
        
        
    """
    
    
    import sys
    sys.setrecursionlimit(10**7)
    from itertools import accumulate, combinations, permutations, product 
    
    from math import factorial, ceil, floor, sqrt
    def factorize(n):
        """return the factors of the Arg and count of each factor
        
        Args:
            n (long): number to be resolved into factors
        
        Returns:
            list of tuples: factorize(220) returns [(2, 2), (5, 1), (11, 1)]
        """
        fct = []  
        b, e = 2, 0  
        while b * b <= n:
            while n % b == 0:
                n = n // b
                e = e + 1
            if e > 0:
                fct.append((b, e))
            b, e = b + 1, 0
        if n > 1:
            fct.append((n, 1))
        return fct
    def combinations_count(n, r):   
        """Return the number of selecting r pieces of items from n kinds of items.
        
        Args:
            n (long): number
            r (long): number
        
        Raises:
            Exception: not defined when n or r is negative
        
        Returns:
            long: number
        """
        
        if n < 0 or r < 0:
            raise Exception('combinations_count(n, r) not defined when n or r is negative')
        if n - r < r: r = n - r
        if r < 0: return 0
        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 combinations_with_replacement_count(n, r):
        """Return the number of selecting r pieces of items from n kinds of items allowing individual elements to be repeated more than once.
        
        Args:
            n (long): number
            r (long): number
        
        Raises:
            Exception: not defined when n or r is negative
        
        Returns:
            long: number
        """
        if n < 0 or r < 0:
            raise Exception('combinations_with_replacement_count(n, r) not defined when n or r is negative')
        elif n == 0:
            return 1
        else:
            return combinations_count(n + r - 1, r)
    from bisect import bisect_left, bisect_right
    from collections import deque, Counter, defaultdict 
    from heapq import heapify, heappop, heappush, heappushpop, heapreplace,nlargest,nsmallest 
    from copy import deepcopy, copy 
    import operator
    from operator import itemgetter 
    
    
    from functools import reduce, lru_cache
    def chmin(x, y):
        """change minimum
        if x > y, x = y and return (x, True).
        convenient when solving problems of dp[i]
        
        Args:
            x (long): current minimum value
            y (long): potential minimum value
        
        Returns:
            (x, bool): (x, True) when updated, else (x, False)
        """
        if x > y:
            x = y
            return (x, True)
        else:
            return (x, False)
    def chmax(x, y):
        """change maximum
        if x < y, x = y and return (x, True).
        convenient when solving problems of dp[i]
        
        Args:
            x (long): current maximum value
            y (long): potential maximum value
        
        Returns:
            (x, bool): (x, True) when updated, else (x, False)
        """
        if x < y:
            x = y
            return (x, True)
        else:
            return (x, False)

    from fractions import gcd 
    def gcds(numbers):
        return reduce(gcd, numbers)
    def lcm(x, y):
        return (x * y) // gcd(x, y)
    def lcms(numbers):
        return reduce(lcm, numbers, 1)
    def make_divisors(n, reversed=False):
        """create list of divisors
        
        Args:
            number (int): number from which list of divisors is created
            reversed (bool, optional): ascending order if False. Defaults to False.
        
        Returns:
            list: list of divisors
        """
        divisors = set()
        for i in range(1, int(n**0.5)+1):
            if n % i == 0:
                divisors.add(i)
                divisors.add(n//i)
        return sorted(list(divisors),reverse=reversed)
    
    
    
    INF = 10 ** 18
    MOD = 10 ** 9 + 7
    AtoZ = list('abcdefghijklmnopqrsruvwxyz') 
    modpow = lambda a, n, p = MOD: pow(a, n, p) 
    def modinv(a, p = MOD):
        
        
        return modpow(a, p-2, p)
    def modinv_list(n, p = MOD):
        if n <= 1:
            return [0,1][:n+1]
        else:
            inv_t = [0,1]
            for i in range(2, n+1):
                inv_t += [inv_t[p % i] * (p - int(p / i)) % p]
            return inv_t
    def modfactorial_list(n, p = MOD):
        if n == 0:
            return [1]
        else:
            l = [0] * (n+1)
            tmp = 1
            for i in range(1, n+1):
                tmp = tmp * i % p
                l[i] = tmp
            return l
    def modcomb(n, k, fac_list = [], p = MOD):
        
        
        from math import factorial
        if n < 0 or k < 0 or n < k: return 0
        if n == 0 or k == 0: return 1
        if len(fac_list) <= n:
            a = factorial(n) % p
            b = factorial(k) % p
            c = factorial(n-k) % p
        else:
            a = fac_list[n]
            b = fac_list[k]
            c = fac_list[n-k]
        return (a * modpow(b, p-2, p) * modpow(c, p-2, p)) % p
    def modadd(a, b, p = MOD):
        return (a + b) % MOD
    def modsub(a, b, p = MOD):
        return (a - b) % p
    def modmul(a, b, p = MOD):
        return ((a % p) * (b % p)) % p
    def moddiv(a, b, p = MOD):
        return modmul(a, modpow(b, p-2, p))

    class UnionFindTree:
        """union find tree class
        TODO: fix this description...
        how to use (example):
        >>  uf = UnionFindTree(N) 
        >>  if uf.find_root(a) == uf.find_root(b):
        >>      do something
        >>  else:
        >>      do something
        >>      uf.unite(a, b)
        """
        def __init__(self, N):
            self.root = [-1] * (N+1)
            self.rank   = [0]  * (N+1)
            self.connected_num = [1] * (N+1)
    
        def find_root(self,x):
            root = self.root
            while root[x] != -1:
                x = root[x]
            return x
    
        def unite(self,x,y):
            root = self.root
            rank = self.rank
            connected_num = self.connected_num
            find_root = self.find_root
    
            rx = find_root(x)
            ry = find_root(y)
            if rx != ry:
                if rank[rx] < rank[ry]:
                    root[rx] = ry
                    rx,ry = ry,rx
                else:
                    if rank[rx] == rank[ry]:
                        rank[rx] += 1
                    root[ry] = rx       
                connected_num[rx] += connected_num[ry]

    class SegTree:
        """
        ref: https://qiita.com/takayg1/items/c811bd07c21923d7ec69
        init(init_val, ide_ele): 配列init_valで初期化 O(N)
        update(k, x): k番目の値をxに更新 O(logN)
        query(l, r): 区間[l, r)をsegfuncしたものを返す O(logN)
        """
        def __init__(self, init_val, segfunc, ide_ele):
            """
            init_val: 配列の初期値
            segfunc: 区間にしたい操作
            ide_ele: 単位元
            n: 要素数
            num: n以上の最小の2のべき乗
            tree: セグメント木(1-index)
            """
            n = len(init_val)
            self.segfunc = segfunc
            self.ide_ele = ide_ele
            self.num = 1 << (n - 1).bit_length()
            self.tree = [ide_ele] * 2 * self.num
            
            for i in range(n):
                self.tree[self.num + i] = init_val[i]
            
            for i in range(self.num - 1, 0, -1):
                self.tree[i] = self.segfunc(self.tree[2 * i], self.tree[2 * i + 1])

        def update(self, k, x):
            """
            k番目の値をxに更新
            k: index(0-index)
            x: update value
            """
            k += self.num
            self.tree[k] = x
            while k > 1:
                self.tree[k >> 1] = self.segfunc(self.tree[k], self.tree[k ^ 1])
                k >>= 1

        def query(self, l, r):
            """
            [l, r)のsegfuncしたものを得る
            l: index(0-index)
            r: index(0-index)
            """
            res = self.ide_ele
            l += self.num
            r += self.num
            while l < r:
                if l & 1:
                    res = self.segfunc(res, self.tree[l])
                    l += 1
                if r & 1:
                    res = self.segfunc(res, self.tree[r - 1])
                l >>= 1
                r >>= 1
            return res

    
    
    
    
    
    
    
    

    def BellmanFord(N, M, ABC, vertex_start, vertex_end, value_if_inf = -1, find_shortest = False):
        """to calculate furthest or shortest length between vertex_start and vertex_end using BellmanFord algorithm
        
        Args:
            N (int): number of vertices
            M (int): number of edges
            ABC (list): [(ai, bi, ci) for _ in range(N)] where i-th edge is directed from vertex ai to vertex bi and the length is ci 
            vertex_start (int): start vertex. usually use 0.
            vertex_end (int): end vertex. usually use N-1.
            value_if_inf (int or string as you like, optional): value you want when the furthest (or shortest) distance is infinite (or -infinite). Defaults to -1.
            find_shortest (bool, optional): choose False to find furthest path. Defaults to False.
        
        Returns:
            int or string: normally int (but can be str if you set value_if_inf to str)
            
        Example:
                N, M, P = R()
                ABC = [R() for _ in range(M)]
                ABC = [(a-1, b-1, c-P) for a, b, c in ABC]
                print(BellmanFord(N, M, ABC, 0, N-1, value_if_inf = 'inf'))

        """

        def make_reachable_list(N, M, ABC, vertex_start, vertex_end):
            reachable_to_direct = defaultdict(list)
            reachable_from_direct = defaultdict(list)
            reachable_from_start = [False] * N
            reachable_to_end = [False] * N
            reachable_from_start[vertex_start] = True
            reachable_to_end[vertex_end] = True
            reachable_from_both_sides = [False] * N
            dfs_from_start = []
            dfs_to_end = []
            for a, b, c in ABC:
                reachable_to_direct[a].append(b)
                reachable_from_direct[b].append(a)
                if a == vertex_start:
                    dfs_from_start.append(b)
                    reachable_from_start[b] = True
                if b == vertex_end:
                    dfs_to_end.append(a)
                    reachable_to_end[a] = True
            while dfs_from_start:
                v = dfs_from_start.pop()
                for i in reachable_to_direct[v]:
                    if not reachable_from_start[i]:
                        reachable_from_start[i] = True
                        dfs_from_start.append(i)
            while dfs_to_end:
                v = dfs_to_end.pop()
                for i in reachable_from_direct[v]:
                    if not reachable_to_end[i]:
                        reachable_to_end[i] = True
                        dfs_to_end.append(i)
            for i in range(N):
                reachable_from_both_sides[i] = reachable_from_start[i] and reachable_to_end[i]
            return reachable_from_both_sides
        
        reachable_from_both_sides = make_reachable_list(N, M, ABC, vertex_start, vertex_end)
        
        if find_shortest:
            dist = [INF for i in range(N)]
        else:
            dist = [-INF for i in range(N)]
        
        dist[vertex_start] = 0
        for i in range(N):
            updated = False
            for a, b, c in ABC:
                if not reachable_from_both_sides[a]:
                    continue
                elif find_shortest:
                    update_condition = dist[a] + c < dist[b]
                else:
                    update_condition = dist[a] + c > dist[b]
                if dist[a] != INF and update_condition:
                    dist[b] = dist[a] + c
                    updated = True
                    if i == N-1:
                        return value_if_inf
            if not updated:
                break
        return dist[vertex_end]

    
    def warshall_floyd(number_vertex, XYD, shift_one_for_vertex=False):
        
        
        
        
        
        d = [[float("inf")]*number_vertex for i in range(number_vertex)]
        for x, y, dist in XYD:
            if shift_one_for_vertex:
                x = x - 1
                y = y - 1
            d[x][y] = dist
            d[y][x] = dist
        for i in range(number_vertex):
            d[i][i] = 0 
        for k in range(number_vertex):
            for i in range(number_vertex):
                for j in range(number_vertex):
                    d[i][j] = min(d[i][j],d[i][k] + d[k][j])
        return d


    """ initialize variables and set inputs
    
        
        
            
            
    
        
        
        
        
        
        
        
    
        
        
        
        
    
        
        
    """

    
    r = lambda: sys.stdin.readline().strip()
    r_int = lambda: int(r())
    r_float = lambda: float(r())
    R = lambda: list(map(int, r().split()))
    R_str = lambda: r().split()
    R_map = lambda: map(int, r().split())
    R_float = lambda: list(map(float, r().split()))
    R_tuple = lambda: tuple(map(int, r().split()))

    """ how to treat input
    
    
    
    
    
    
    
    """

    
    if sample_file:
        sys.stdin = open(sample_file)
        
    
    
    

    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    N = r_int()
    A = R()
    ans = 0
    A.sort(reverse=True)
    l = deque()
    for i, a in enumerate(A):
        if i == 0:
            l.append(a)
        else:
            ans += l.popleft()
            l.append(a)
            l.append(a)
            
    print(ans)
    

    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    

    
    
    
    
    
    
    
    
    
    
    
    
    
    

    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    

    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    

    


    
    
    

    """memo: how to use defaultdict of list
    
    Dic = defaultdict(list)
    
    Dic[x].append(y)
    
    for k, v in Dic.items():
    """
    
    """memo: how to solve binary problems
    
    >>> a = 5
    >>> bin_str_a = format(a, '
    >>> print(bin_str_a)
    0b0101 
    """
    
    """memo: how to solve the problem
    creating simple test/answer
    greed
    simple dp
    graph
    """

if __name__ == '__main__':
    main()

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

ans=max(a)
cnt=0
for i in range(1,n):
  now=a[i]
  for s in range(2):
    if cnt+1<=n-2:
      ans+=now
      cnt+=1
print(ans)

Solution (Python):

import sys
input = sys.stdin.readline
N = int(input())
A = list(map(int, input().split()))
A.sort(reverse =True)
A1 =A[1:] +A[1:]
A1.sort(reverse =True)
ans =[A[0]] +A1


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

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

A.sort()
ans = 0
tmp = 0
for i in range(N):
    if i == 0:
        continue
    elif i == 1:
        ans += A.pop()
    elif i % 2 == 0:
        tmp = A.pop()
        ans += tmp
    else:
        ans += tmp
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):
t=int(input())
arr1=list(map(int,input().strip().split()))[:t]
y=max(arr1)
arr1.sort(reverse= True)
summ=0
l1=[]
l1.append(y)
w=len(arr1)
for x in range(1,w):
  l1.append(arr1[x])
  l1.append(arr1[x])
j=0
for x in range(1,w):
  summ=summ+l1[j]
  j+=1
print(summ)

Solution (Python):
import collections

def resolve():
  N = int(input())
  A = [int(x) for x in input().split(" ")]
  setA = set(A)
  listA = sorted(list(setA))
  collectionA = collections.Counter(A)

  result = listA[-1]
  collectionA[listA[-1]] -= 1

  if collectionA[listA[-1]] == 0:
    listA.pop()

  for list_a in listA:
    collectionA[list_a] *= 2

  for i in range(N - 2):
    result += listA[-1]
    collectionA[listA[-1]] -= 1
    if collectionA[listA[-1]] == 0:
      listA.pop()

  print(result)


if __name__ == "__main__":
  resolve()

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

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


if N==2:
    out=A[-1]

else:
    out=A[-1]
    flag=0
    cnt=1
    i=1
    while cnt<N-1:
        if flag==0:
            flag=1
            out+=A[-1*(i+1)]
        elif flag==1:
            out+=A[-1*(i+1)]
            i+=1
            flag=0

        
        cnt+=1

print(out)

Solution (Python):


N = int(input())

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

A_sort = sorted(A)
sum_num = A_sort.pop(-1)

i = 2
while i + 2 <= N:
    sum_num += A_sort.pop(-1) * 2
    i += 2

if i + 1 <= N:
    sum_num += A_sort.pop(-1)

print(sum_num)

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

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

A = sorted(A, reverse = True)
import heapq as hq
q = []
ans = 0
for i in range(len(A)):
  if q:
    ans += -hq.heappop(q)
  for j in range(min(i + 1,2)):
    hq.heappush(q, -A[i])
    
print(ans)

Solution (Python):
n,*l=map(int,open(0).read().split());print(sum(sorted(l*2)[-2:~n:-1]))

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

A.sort()
ans = 0
tmp = 0
for i in range(N):
    if i == 0:
        continue
    elif i == 1:
        ans += A.pop()
    elif i % 2 == 0:
        tmp = A.pop()
        ans += tmp
    else:
        ans += tmp
print(ans)

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

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

print(ans)

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

A.sort(reverse = True)
ans = A[0]
i = 1
count = 1

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

print(ans)

Solution (Python):
from collections import deque
import math
import os
import random
import re
import sys


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

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

Solution (Python):
import sys, os, math, bisect, itertools, collections, heapq, queue

from decimal import Decimal
from collections import defaultdict, deque

sys.setrecursionlimit(10000000)

ii = lambda: int(sys.stdin.buffer.readline().rstrip())
il = lambda: list(map(int, sys.stdin.buffer.readline().split()))
fl = lambda: list(map(float, sys.stdin.buffer.readline().split()))
iln = lambda n: [int(sys.stdin.buffer.readline().rstrip()) for _ in range(n)]

iss = lambda: sys.stdin.buffer.readline().decode().rstrip()
sl = lambda: list(map(str, sys.stdin.buffer.readline().decode().split()))
isn = lambda n: [sys.stdin.buffer.readline().decode().rstrip() for _ in range(n)]

lcm = lambda x, y: (x * y) // math.gcd(x, y)

MOD = 10 ** 9 + 7
MAX = float('inf')


def main():
    if os.getenv("LOCAL"):
        sys.stdin = open("input.txt", "r")

    N = ii()
    A = sorted(il(), reverse=True)

    ret = 0
    for n in range(1, N):
        ret += A[(N - n) // 2]
    print(ret)


if __name__ == '__main__':
    main()

Solution (Python):
import sys

def I(): return int(sys.stdin.readline().rstrip())
def LI(): return list(map(int,sys.stdin.readline().rstrip().split()))  

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
def main():
    N = int(input())
    A = list(map(int, input().split()))
    A.sort()
    ans = A[-1]
    ans_cnt = 0
    for i in range(N-1)[::-1]:
        if ans_cnt == N-2:
            break
        ans += A[i]
        ans_cnt += 1
        if ans_cnt == N-2:
            break
        ans += A[i]
        ans_cnt += 1
        if ans_cnt == N-2:
            break
    print(ans)
if __name__ == "__main__":
    main()

Solution (Python):
import heapq
n = int(input())
a_lst = list(map(int, input().split(" ")))

a_lst.sort(reverse=True)


result = 0
heap = []
heapq.heappush(heap,-a_lst[0])

for i in a_lst[1:]:
	now_max = heapq.heappop(heap)
	result += now_max
	heapq.heappush(heap, -i)
	heapq.heappush(heap, -i)

print(-result)

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

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

Solution (Python):
def main():
    import sys
    def input(): return sys.stdin.readline().rstrip()
    n = int(input())
    a = list(map(int, input().split()))
    a.sort(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])



if __name__ == '__main__':
    main()

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

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

ans = a[0]

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

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


print(ans)

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

Solution (Python):

"""
Created on Sun Jul  5 22:49:34 2020

@author: Aruto Hosaka
"""


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

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

Solution (Python):
n = int(input())
a = [int(i) for i in input().split()]
a.sort(reverse=True)
ans = a[0]
idx = 1
flag = False
for i in range(n-2):
    ans += a[idx]
    if flag:
        idx += 1
        flag = False
    else:
        flag = True
print(ans)

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

Solution (Python):
if __name__ == '__main__':
    n = int(input().strip())
    A = list(map(int, input().strip().split()))
    A.sort(reverse=True)

    score = A[0] + sum([A[1+int(i/2)]for i in range(0, n-2)])

    print(score)

Solution (Python):

import sys
from collections import deque

def solve(N: int, A: "List[int]"):
    sorted_list = list(reversed(sorted(A)))
    score = 0
    queue = deque()
    queue.append(sorted_list[0])
    cnt_map = {sorted_list[0]: 1}
    for i in range(1, len(sorted_list)):
        current_max = queue[0]
        score += current_max
        cnt_map[current_max] -= 1
        num = sorted_list[i]
        if num in cnt_map:
            cnt_map[num] += 2
        else:
            cnt_map[num] = 2
            queue.append(num)

        if cnt_map[current_max] == 0:
            queue.popleft()
    print(score)
    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):
"""
    Satwik_Tiwari ;) .
    4th july , 2020  - Saturday
"""



from __future__ import division, print_function

from fractions import Fraction
import sys
import os
from io import BytesIO, IOBase


import bisect
from heapq import *
from math import *
from collections import deque
from collections import Counter as counter  
from itertools import combinations as comb 
from itertools import permutations as permutate
from bisect import bisect_left as bl


from bisect import bisect_right as br
from bisect import bisect





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)






mod = 1000000007
def inp(): return sys.stdin.readline().rstrip("\r\n") 
def out(var): sys.stdout.write(str(var))  
def lis(): return list(map(int, inp().split()))
def stringlis(): return list(map(str, inp().split()))
def sep(): return map(int, inp().split())
def strsep(): return map(str, inp().split())

def zerolist(n): return [0]*n
def nextline(): out("\n")  
def testcase(t):
    for p in range(t):
        solve()
def printlist(a) :
    for p in range(0,len(a)):
        out(str(a[p]) + ' ')
def lcm(a,b): return (a*b)//gcd(a,b)
def power(a,b):
    ans = 1
    while(b>0):
        if(b%2==1):
            ans*=a
        a*=a
        b//=2
    return ans
def ncr(n,r): return factorial(n)//(factorial(r)*factorial(max(n-r,1)))
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 bs(a,l,h,x):
    while(l<h):
        
        mid = (l+h)//2
        if(a[mid] == x):
            return mid
        if(a[mid] < x):
            l = mid+1
        else:
            h = mid
    return l

def sieve(a): 
    
    for i in range(3,((10**6)+1),2):
        a[i] = 1
    
    for i in range(3,((10**6)+1),2):
        for j in range(i*i,((10**6)+1),i):
            a[j] = 0
    a[2] = 1 
    return (a)


def bfs(g,st):
    visited = [-1]*(len(g))
    visited[st] = 0
    queue = []
    queue.append(st)
    new = []
    while(len(queue) != 0):
        s = queue.pop()
        new.append(s)
        for i in g[s]:
            if(visited[i] == -1):
                visited[i] = visited[s]+1
                queue.append(i)
    return visited


def dfsusingstack(v,st):
    d = deque([])
    visited = [0]*(len(v))
    d.append(st)
    new = []
    visited[st] = 1
    while(len(d) != 0):
        curr = d.pop()
        new.append(curr)
        for i in v[curr]:
            if(visited[i] == 0):
                visited[i] = 1
                d.append(i)
    return new


def solve():
    n = int(inp())
    a = sorted(lis())[::-1]
    cnt = n-1
    ans = a[0]
    cnt-=1
    st = 1
    while(cnt>0):
        if(cnt>1):
            ans+=2*a[st]
            st+=1
            cnt-=2
        else:
            ans+=a[st]
            st+=1
            cnt-=1
    print(ans)









testcase(1)