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



Sample input:
4
2 2 1 3


Sample output:
7

Submission status: Accepted

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

Submission status: Accepted

Solution code:
N = int(input())
A = list(map(int,input().split()))
A.sort()
ans = A[-1]
i = N-1
N -= 2
while N:
    i -= 1
    for _ in range(2):
        N -= 1
        ans += A[i]
        if N<=0: break
print(ans)

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(10**7) #再帰関数の上限,10**5以上の場合python
import math
from copy import copy, deepcopy
from copy import deepcopy as dcp
from operator import itemgetter
from bisect import bisect_left, bisect, bisect_right#2分探索
#bisect_left(l,x), bisect(l,x)#aはソート済みである必要あり。aの中からx未満の要素数を返す。rightだと以下
from collections import deque, defaultdict
#deque(l), pop(), append(x), popleft(), appendleft(x)
#q.rotate(n)で → にn回ローテート
from collections import Counter#文字列を個数カウント辞書に、
#S=Counter(l),S.most_common(x),S.keys(),S.values(),S.items()
from itertools import accumulate,combinations,permutations#累積和
#list(accumulate(l))
from heapq import heapify,heappop,heappush
#heapify(q),heappush(q,a),heappop(q) #q=heapify(q)としないこと、返り値はNone
#import fractions#古いatcoderコンテストの場合GCDなどはここからimportする
from functools import reduce,lru_cache#pypyでもうごく
#@lru_cache(maxsize = None)#maxsizeは保存するデータ数の最大値、2**nが最も高効率
from decimal import Decimal

def input(): 
    x=sys.stdin.readline()
    return x[:-1] if x[-1]=="\n" else x
def printe(*x):print("## ",*x,file=sys.stderr)
def printl(li): _=print(*li, sep="\n") if li else None
def argsort(s, return_sorted=False): 
    inds=sorted(range(len(s)), key=lambda k: s[k])
    if return_sorted: return inds, [s[i] for i in inds]
    return inds
def alp2num(c,cap=False): return ord(c)-97 if not cap else ord(c)-65
def num2alp(i,cap=False): return chr(i+97) if not cap else chr(i+65)
def matmat(A,B):
    K,N,M=len(B),len(A),len(B[0])
    return [[sum([(A[i][k]*B[k][j]) for k in range(K)]) for j in range(M)] for i in range(N)]
def matvec(M,v):
    N,size=len(v),len(M)
    return [sum([M[i][j]*v[j] for j in range(N)]) for i in range(size)]
def T(M):
    n,m=len(M),len(M[0])
    return [[M[j][i] for j in range(n)] for i in range(m)]
def main():
    mod = 1000000007
    #w.sort(key=itemgetter(1),reverse=True)  #二個目の要素で降順並び替え

    N = int(input())
    #N, K = map(int, input().split())
    A = list(map(int, input().split())) #1行ベクトル
    #L = tuple(int(input()) for i in range(N)) #改行ベクトル
    #S = tuple(tuple(map(int, input().split())) for i in range(N)) #改行行列

    A.sort(reverse=True)
    ans=0
    ma=A[0]
    l=deque([A[0]])
    for a in A[1:]:
        ans+=l.popleft()
        l.append(a)
        l.append(a)
    print(ans)





if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
from sys import stdin
n = int(stdin.readline())
arr = sorted(list(map(int,stdin.readline().split())),reverse=True)
ans = arr[0]
peo = n-2
i = 1
while peo > 0:
    if peo == 1:
        ans += arr[i]
        peo -= 1
    else:
        ans += 2*arr[i]
        peo -= 2
        i += 1
print(ans)

Submission status: Accepted

Solution code:
from collections import deque
n = int(input())
a = list(map(int,input().split()))
a.sort(reverse=True)
ans = 0
que = deque()
que.append(a[0])
for i in range(1,n):
    ans+=que.popleft()
    que.append(a[i])
    que.append(a[i])
print(ans)

Submission status: Accepted

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

Submission status: Accepted

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

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

for i in range(N):
    if i == 0:
        ans = 0
    else:
        idx = i // 2
        # print("#", idx)
        ans += A[idx]

print(ans)

Submission status: Accepted

Solution code:
N = int(input())
A = [int(x) for x in input().split()]
A.sort(reverse=True)

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

Submission status: Accepted

Solution code:
import queue
n = int(input())
a = sorted(list(map(int,input().split())), reverse=True)
ans = 0
b = queue.Queue()
b.put(a[0])
for x in a[1:]:
    y = b.get()
    ans += y
    b.put(x)
    b.put(x)
print(ans)

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(10**8)
input = sys.stdin.readline
N = int(input())
A = list(map(int,input().split()))
A.sort(reverse=True)
ans = A[0]
cnt = 2
for i in range(1,N):
    if cnt>=N:
        break
    ans += A[i]
    cnt += 1
    if cnt==N:
        break
    ans += A[i]
    cnt += 1
    if cnt==N:
        break
print(ans)

Submission status: Accepted

Solution code:
import sys,queue,math,copy,itertools,bisect,collections,heapq

def main():
    sys.setrecursionlimit(10**7)
    INF = 10**18
    MOD = 10**9 + 7
    LI = lambda : [int(x) for x in sys.stdin.readline().split()]
    _LI = lambda : [-int(x) for x in sys.stdin.readline().split()]
    NI = lambda : int(sys.stdin.readline())
    SI = lambda : sys.stdin.readline().rstrip()
    DD = ((1,0),(0,1),(-1,0),(0,-1))

    N = NI()
    A = LI()

    A.sort(reverse=True)

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



if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import sys
from collections import defaultdict, Counter, namedtuple, deque
import itertools
import functools
import bisect
import heapq
import math
import copy
# from fractions import gcd

MOD = 10 ** 9 + 7
# MOD = 998244353
# sys.setrecursionlimit(10**8)


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

p = A[0]
rem = n-2
idx = 1
while rem > 0:
    p += A[idx]
    rem -= 1
    if rem == 0:
        break
    p += A[idx]
    rem -= 1
    idx += 1

print(p)

Submission status: Accepted

Solution code:
n = int(input())
a = list(map(int, input().split()))
a.sort(reverse=True)
b = (n-2)//2
c = (n-2)%2
ans = a[0] + sum(a[1:b+1])*2 + a[b+1]*c
print(ans)

Submission status: Accepted

Solution code:
import heapq
n = int(input())
a = list(map(int, input().split()))

inf = 10**9 + 1
a.sort()
first = a.pop()
heap = [[-first, first, inf]]
ans = 0
while a:
    x, left, right = heapq.heappop(heap)
    ans += x
    t = a.pop()
    heapq.heappush(heap, [-min(t, left), left, t])
    heapq.heappush(heap, [-min(t, right), t, right])

print(-ans)

Submission status: Accepted

Solution code:
n=int(input())
l=list(map(int, input().split()))
l.sort(reverse=True)
com=l[0]
j=1
for i in range(2,n):
    com=com+l[j]
    if i%2==1:
        j=j+1
print(com)

Submission status: Accepted

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

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

Submission status: Accepted

Solution code:
def main():
    import sys
    input = sys.stdin.readline
    sys.setrecursionlimit(10**7)
    from collections import Counter, deque
    from itertools import combinations, permutations, accumulate, groupby, product
    from bisect import bisect_left,bisect_right
    from heapq import heapify, heappop, heappush
    import math
    #from math import gcd

    #inf = 10**17
    #mod = 10**9 + 7
    #epsilon = 10**-9

    n = int(input())
    a = list(map(int, input().split()))
    a.sort(reverse=True)
    res = a[0]
    n -= 2
    i = 1
    while n>0:
        res += a[i]
        n -= 1
        if n == 0:
            break
        res += a[i]
        n -= 1
        i += 1

    print(res)

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
from sys import stdin, setrecursionlimit
#input = stdin.buffer.readline
setrecursionlimit(10 ** 7)

from heapq import heappush, heappop
from bisect import bisect_left, bisect_right
from collections import deque, defaultdict, Counter
from itertools import combinations, permutations, combinations_with_replacement
from itertools import accumulate
from math import ceil, sqrt, pi, radians, sin, cos

MOD = 10 ** 9 + 7
INF = 10 ** 18

N = int(input())
#S = input()
#N, M = map(int, input().split())
A = list(map(int, input().split()))
#A = [int(input()) for _ in range(N)]
#ABC = [list(map(int, input().split())) for _ in range(N)]

A.sort(reverse = True)
h = [-A[0]]

answer = 0
for a in A[1:]:
    answer -= heappop(h)
    heappush(h, -a)
    heappush(h, -a)

print(answer)

Submission status: Accepted

Solution code:
import heapq
N = int(input())
A = list(map(int,input().split()))
A.sort(reverse=True)
heaplist = []
heapq.heappush(heaplist,-A[0])
ans = 0
for i in range(1,N):
    ans -= heapq.heappop(heaplist)
    heapq.heappush(heaplist,-A[i])
    heapq.heappush(heaplist,-A[i])

print(ans)

Submission status: Accepted

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

Submission status: Accepted

Solution code:
# coding: utf-8
# hello worldと表示する
#float型を許すな
#numpyはpythonで
import sys
input = sys.stdin.readline
sys.setrecursionlimit(10**7)
from collections import Counter, deque
from collections import defaultdict
from itertools import combinations, permutations, accumulate, groupby, product
from bisect import bisect_left,bisect_right
from heapq import heapify, heappop, heappush
from math import floor, ceil,pi,factorial
from operator import itemgetter
def I(): return int(input())
def MI(): return map(int, input().split())
def LI(): return list(map(int, input().split()))
def LI2(): return [int(input()) for i in range(n)]
def MXI(): return [[LI()]for i in range(n)]
def SI(): return input().rstrip()
def printns(x): print('\n'.join(x))
def printni(x): print('\n'.join(list(map(str,x))))
inf = 10**17
mod = 10**9 + 7
n=I()
lis=LI()
lis.sort(reverse=True)
nl=[]
nl.append(lis[0])
for i in range(1,n):
    nl.append(lis[i])
    nl.append(lis[i])
ans=0
#print(nl)
for i in range(n-1):
    ans+=nl[i]
print(ans)

Submission status: Accepted

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

b = []
for i in range(1, n):
    b.append(a[i])
    b.append(a[i])
ans = a[0]
ans += sum(b[:n-2])
print(ans)

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

Solution code:
from collections import Counter
import sys

sys.setrecursionlimit(10 ** 6)

mod = 1000000007
inf = int(1e18)

dx = [0, 1, 0, -1]
dy = [1, 0, -1, 0]


def inverse(a):
    return pow(a, mod - 2, mod)


def usearch(x, a):
    lft = 0
    rgt = len(a) + 1
    while rgt - lft > 1:
        mid = (rgt + lft) // 2
        if a[mid] <= x:
            lft = mid
        else:
            rgt = mid
    return lft



def main():
    n = int(input())
    a = sorted(map(int, input().split()))[::-1]
    s = a[0]
    i = 1
    c = 2
    while c < n:
        s += a[i]
        c += 1
        if c < n:
            s += a[i]
            c += 1
        i += 1
    print(s)
main()

Submission status: Accepted

Solution code:
from heapq import heappush, heappop
n = int(input())
a = list(map(int, input().split()))
a.sort(reverse=True)
ans = 0
d = [-a[0]]
for ai in a[1:]:
    nxt = -heappop(d)
    ans += nxt
    heappush(d, -ai)
    heappush(d, -ai)
print(ans)

Submission status: Accepted

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

ans,point,index=0,0,0
for i in range(n-1):
    ans +=A[index]
    point +=1
    if index==0 or point==2:
        index +=1
        point=0
print(ans)

Submission status: Accepted

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

Submission status: Accepted

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

A.sort(reverse=True)
ret = A[0]
c = N - 2
i = 1
while c :
  if c >= 2 :
    ret += A[i] * 2
    c -= 2
  else :
    ret += A[i]
    c -= 1
  i += 1

print(ret)

Submission status: Accepted

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

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

Submission status: Accepted

Solution code:
N = int(input())
A = list(map(int,input().split()))
A.sort()
print(sum(A[N//2:])*2-A[-1]-(N%2)*A[N//2])

Submission status: Accepted

Solution code:
N = int(input())
As = list(map(int, input().split()))

As.sort(reverse=True)
#print('As:', As)

ans = As[0]
i = 1
num = 0
for _ in range(N-2):
    ans += As[i]
    num += 1
    if num >= 2:
        i += 1
        num = 0

print(ans)

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline

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

sa = sorted(A, reverse=True)

res = 2 * sum(sa[:N//2]) - sa[0]
if N % 2:
    res += sa[N//2]

print(res)

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
import bisect
import heapq
import math
import random
from collections import Counter, defaultdict, deque
from decimal import ROUND_CEILING, ROUND_HALF_UP, Decimal
from functools import lru_cache, reduce
from itertools import combinations, combinations_with_replacement, product, permutations
from operator import add, mul, sub


import sys
# sys.setrecursionlimit(10**6)
# buff_readline = sys.stdin.buffer.readline
buff_readline = sys.stdin.readline
readline = sys.stdin.readline

INF = 2**62-1


def read_int():
    return int(buff_readline())


def read_int_n():
    return list(map(int, buff_readline().split()))


def read_float():
    return float(buff_readline())


def read_float_n():
    return list(map(float, buff_readline().split()))


def read_str():
    return readline().strip()


def read_str_n():
    return readline().strip().split()

def error_print(*args):
    print(*args, file=sys.stderr)


def mt(f):
    import time

    def wrap(*args, **kwargs):
        s = time.time()
        ret = f(*args, **kwargs)
        e = time.time()

        error_print(e - s, 'sec')
        return ret

    return wrap


@mt
def slv(N, A):
    A.sort()
    q = []
    a = A.pop()
    ans = a
    a = A.pop()
    heapq.heappush(q, -a)
    heapq.heappush(q, -a)
    while A:
        a = A.pop()
        ans += -heapq.heappop(q)
        heapq.heappush(q, -a)
        heapq.heappush(q, -a)
    return ans


def main():
    N = read_int()
    A = read_int_n()
    print(slv(N, A))


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
N = int(input())
A = [int(_) for _ in input().split()]

comfort = 0
A.sort(reverse=True)
top = 0
count = 0
for i in range(1,N):
  if i == 1:
    comfort += A[top]
    top += 1
  else:
    comfort += A[top]
    if count == 1:
      top += 1
      count = 0
    else:
      count = 1
print(comfort)

Submission status: Accepted

Solution code:
it = lambda: list(map(int, input().strip().split()))

def solve():
    N = int(input())
    A = it()
    if N == 1:
        return 0
        
    A.sort(reverse=True)

    ans = A[0]
    n = N - 2
    i = 1
    while n > 0:
        if n >= 2:
            ans += 2 * A[i]
            n -= 2
        else:
            ans += A[i]
            n -= 1
        i += 1
    return ans


if __name__ == '__main__':
    print(solve())

Submission status: Accepted

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

Submission status: Accepted

Solution code:
import sys
readline = sys.stdin.buffer.readline
def even(n): return 1 if n%2==0 else 0

n = int(readline())
lst1 = list(map(int,readline().split()))

lst1.sort(reverse=True)
ans = 0
idx = 0
remain = 1
for i in range(n):
    if i == 0:
        continue
    if remain:
        remain -= 1
    else:
        remain = 1
        idx += 1
    ans += lst1[idx]
    


print(ans)

Submission status: Accepted

Solution code:
import heapq
N=int(input())
A=list(map(int,input().split()))
A.sort(reverse=True)
ans=0
line=[]
heapq.heappush(line,-A[0])
for i in range(1,N):
    ans-=heapq.heappop(line)
    heapq.heappush(line,-A[i])
    heapq.heappush(line,-A[i])
print(ans)

Submission status: Accepted

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

Submission status: Accepted

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

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

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

print(ans)

Submission status: Accepted

Solution code:
n=int(input())
a=list(map(int,input().split()))
a.sort()
a.reverse()
n-=1
ans=a[0]
n-=1
y=1
for i in range(n):
  ans+=a[y]
  if i%2==1:
    y+=1
print(ans)

Submission status: Accepted

Solution code:
from collections import deque
import sys


def read_int():
    line = sys.stdin.readline().rstrip('\n')
    return int(line)

def read_int_list():
    line = sys.stdin.readline().rstrip('\n')
    return [int(e) for e in line.split(' ')]

N = read_int()
A = read_int_list()

A.sort(key=lambda i:-i) # descending                                                                                                                          

q = deque()

ans = 0
for i in A:
    if q:
        ans += q.popleft()
        q.append(i)
    q.append(i)
print(ans)

Submission status: Accepted

Solution code:
n=int(input())
A=[int(i) for i in input().split()]
A.sort()
stc=[A.pop()]
now=0
ans=0
while len(A)>0:
    new=A.pop()
    stc.append(new)
    stc.append(new)
    ans+=stc[now]
    now+=1

print(ans)

Submission status: Accepted

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

Submission status: Accepted

Solution code:
# coding: utf-8
# Your code here!
import sys
read = sys.stdin.read
readline = sys.stdin.readline

n,*a = map(int,read().split())
a.sort(reverse=True)


ans = -a[0]
for i in range(n):
    ans += a[i>>1]

print(ans)

Submission status: Accepted

Solution code:
import sys, bisect, math, itertools, string, queue, copy
# import numpy as np
# import scipy
# from scipy.sparse.csgraph import floyd_warshall
from collections import Counter,defaultdict,deque
from itertools import permutations, combinations, combinations_with_replacement
from heapq import heappop, heappush, heapify
from fractions import gcd
# input = sys.stdin.readline
sys.setrecursionlimit(10**8)
mod = 10**9+7

def main():
    n = int(input())
    a = list(map(int,input().split()))
    a.sort(reverse = True)
    ans = 0
    que = deque()
    ans = 0
    que.append(a[0])
    for i in range(1,n):
        ans += que.popleft()
        que.append(a[i])
        que.append(a[i])
    print(ans)

if __name__ == "__main__":
    main()

Submission status: Accepted

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

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

print(ans)

Submission status: Accepted

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

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

Submission status: Accepted

Solution code:

from collections import deque



# for #!/usr/bin/env python
import os
import sys
from io import BytesIO, IOBase


# region fastio

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")
from bisect import bisect_left as bl
from math import log2,ceil
from heapq import heappush, heappop
from itertools import permutations 
def main():
    # for t in range(int(input())):
        n = int(input())
        # d = dict()
        l = [int(j) for j in input().split()]
        l.sort(reverse=True)
        ans = l[0]
        j = 1
        for i in range((n-2)//2):
            # print(i)
            ans+=l[j]*2
            j+=1
        # print(ans)
        if n%2==1:
            ans+=l[j]
        print(ans)

            # heappush(h, l[i])

        


        
        




# endregion

if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
import sys, bisect, math, itertools, heapq, collections
from operator import itemgetter
# a.sort(key=itemgetter(i)) # i番目要素でsort
from functools import lru_cache
# @lru_cache(maxsize=None)
sys.setrecursionlimit(10**8)
input = sys.stdin.readline
INF = float('inf')
mod = 10**9 + 7
eps = 10**-7


def inp():
    '''
    一つの整数
    '''
    return int(input())


def inpl():
    '''
    一行に複数の整数
    '''
    return list(map(int, input().split()))


def str_inp():
    '''
    文字列をリストとして読み込む
    '''
    return list(input()[:-1])


n = inp()
a = inpl()
a.sort(reverse=True)
tmp = 1
now = 0
ans = 0
for i in range(n - 1):
    ans += a[now]
    tmp += 1
    if tmp == 2:
        tmp = 0
        now += 1
print(ans)

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
import sys
import math
import os
import itertools
import string
import heapq
import _collections
from collections import Counter
from collections import defaultdict
from collections import deque
from functools import lru_cache
import bisect
import re
import queue
import copy
import decimal


class Scanner():
    @staticmethod
    def int():
        return int(sys.stdin.readline().rstrip())

    @staticmethod
    def string():
        return sys.stdin.readline().rstrip()

    @staticmethod
    def map_int():
        return [int(x) for x in Scanner.string().split()]

    @staticmethod
    def string_list(n):
        return [Scanner.string() for i in range(n)]

    @staticmethod
    def int_list_list(n):
        return [Scanner.map_int() for i in range(n)]

    @staticmethod
    def int_cols_list(n):
        return [Scanner.int() for i in range(n)]


class Math():
    @staticmethod
    def gcd(a, b):
        if b == 0:
            return a
        return Math.gcd(b, a % b)

    @staticmethod
    def lcm(a, b):
        return (a * b) // Math.gcd(a, b)

    @staticmethod
    def divisor(n):
        lower, upper = [], []
        i = 1
        while i * i <= n:
            if n % i == 0:
                lower.append(i)
                if i != n // i:
                    upper.append(n // i)
            i += 1
        return lower + upper[::-1]

    @staticmethod
    def round_up(a, b):
        return -(-a // b)

    @staticmethod
    def is_prime(n):
        if n < 2:
            return False
        if n == 2:
            return True
        if n % 2 == 0:
            return False
        d = int(n ** 0.5) + 1
        for i in range(3, d + 1, 2):
            if n % i == 0:
                return False
        return True

    @staticmethod
    def fact(N):
        res = {}
        tmp = N
        for i in range(2, int(N ** 0.5 + 1) + 1):
            cnt = 0
            while tmp % i == 0:
                cnt += 1
                tmp //= i
            if cnt > 0:
                res[i] = cnt
        if tmp != 1:
            res[tmp] = 1
        if res == {}:
            res[N] = 1
        return res


def pop_count(x):
    x = x - ((x >> 1) & 0x5555555555555555)
    x = (x & 0x3333333333333333) + ((x >> 2) & 0x3333333333333333)
    x = (x + (x >> 4)) & 0x0f0f0f0f0f0f0f0f
    x = x + (x >> 8)
    x = x + (x >> 16)
    x = x + (x >> 32)
    return x & 0x0000007f


def solve():
    N = Scanner.int()
    A = Scanner.map_int()
    ans = 0
    j = 0
    A.sort(reverse=True)
    for i in range(1, N):
        ans += A[j]
        if i % 2 == 1:
            j += 1
    print(ans)


def main():
    # sys.setrecursionlimit(1000000)
    # sys.stdin = open("sample.txt")
    # T = Scanner.int()
    # for _ in range(T):
    #     solve()
    # print('YNeos'[not solve()::2])
    solve()


if __name__ == "__main__":
    main()

Submission status: Accepted

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

Submission status: Accepted

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


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
def main():
    N = int(input())
    A = [int(i) for i in input().split()]
    ans = 0
    A.sort()
    ans += A.pop()
    for i in range((N-2)//2):
        ans += 2*A.pop()
    if N % 2 == 1:
        ans += A.pop()
    print(ans)


if __name__ == '__main__':
    main()

Submission status: Accepted

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

Submission status: Accepted

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

ans=A[0]
if N>2:
    p = (N-2)//2
    q = (N-2)%2
    ans += 2*sum(A[1:1+p])
    if q==1:
        ans += A[1+p]

print(ans)

Submission status: Accepted

Solution code:
import bisect
import sys
import math
from collections import deque
from heapq import heappush, heappop

def sRaw():
    return input().rstrip("\r")


def iRaw():
    return int(input())


def ssRaw():
    return input().split()


def isRaw():
    return list(map(int, ssRaw()))


INF = 1 << 29

#DIV = (10**9) + 7
DIV = 998244353

def mod_inv_prime(a, mod=DIV):
    return pow(a, mod-2, mod)


def mod_inv(a, b):
    r = a
    w = b
    u = 1
    v = 0
    while w != 0:
        t = r//w
        r -= t*w
        r, w = w, r
        u -= t*v
        u, v = v, u
    return (u % b+b) % b


def CONV_TBL(max, mod=DIV):
    fac, finv, inv = [0]*max, [0]*max, [0]*max
    fac[0] = fac[1] = 1
    finv[0] = finv[1] = 1
    inv[1] = 1
    for i in range(2, max):
        fac[i] = fac[i-1]*i % mod
        inv[i] = mod - inv[mod % i] * (mod//i) % mod
        finv[i] = finv[i-1]*inv[i] % mod

    class CONV:
        def __init__(self):
            self.fac = fac
            self.finv = finv
            pass

        def ncr(self, n, k):
            if(n < k):
                return 0
            if(n < 0 or k < 0):
                return 0
            return fac[n]*(finv[k]*finv[n-k] % DIV) % DIV

    return CONV()


def cumsum(As):
    s = 0
    for a in As:
        s += a
        yield s


sys.setrecursionlimit(200005)


def dijkstra(G,start=0):
    heap = []
    cost = [INF]*len(G)
    heappush(heap,(0,start))
    while len(heap)!=0:
        c,n = heappop(heap)
        if cost[n] !=INF:
            continue
        cost[n]=c
        for e in G[n]:
            ec,v = e
            if cost[v]!=INF:
                continue
            heappush(heap,(ec+c,v))
    return cost


def main():
    N = iRaw()
    As = isRaw()
    As.sort(reverse=True)
    ans = As[0]
    n=2
    idx=1
    while n<N:
        ans+=As[idx]
        n+=1
        if n>=N:
            break
        ans+=As[idx]
        n+=1
        idx+=1
        if n>=N:
            break
    print(ans)
    
main()

Submission status: Accepted

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

cnt = n-1
i = 0
ans = 0
while cnt:
    if i == 0:
        cnt -= 1
        ans += A[i]
        i += 1
    else:
        if cnt < 2:
            ans += A[i]*cnt
            cnt = 0
        else:
            ans += A[i]*2
            cnt -= 2
            i += 1
print(ans)

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(10 ** 8)

def Z(): return int(input())
def ZZ(): return [int(_) for _ in input().split()]

def main():
    N = Z()
    A = sorted(ZZ())[::-1]
    ans = A[0]
    j = 1
    for i in range(N-2):
        ans += A[j]
        if i%2 == 1: j += 1
    print(ans)

    return

if __name__ == '__main__':
    main()