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:
#!usr/bin/env python3
from collections import defaultdict, deque, Counter, OrderedDict
import collections, heapq, itertools, bisect
import math, fractions
import sys, copy

def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI1(): return [int(x) - 1 for x in sys.stdin.readline().split()]
def I(): return int(sys.stdin.readline().rstrip())
def LS(): return [list(x) for x in sys.stdin.readline().split()]
def S(): return list(sys.stdin.readline().rstrip())
def IR(n): return [I() for i in range(n)]
def LIR(n): return [LI() for i in range(n)]
def SR(n): return [S() for i in range(n)]
def LSR(n): return [LS() for i in range(n)]

sys.setrecursionlimit(1000000)
dire = [[1, 0], [0, 1], [-1, 0], [0, -1]]
dire8 = [[1, 0], [1, 1], [0, 1], [-1, 1], [-1, 0], [-1, -1], [0, -1], [1, -1]]
MOD = 1000000007

def main():
    N = I()
    A = sorted(LI(), reverse=True)
    q = []
    ans = A[0]
    q.append((-min(A[0], A[1]), A[0], A[1]))
    q.append((-min(A[0], A[1]), A[0], A[1]))


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

    print(ans)


if __name__ == '__main__':
    main()

Submission status: Accepted

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

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.buffer.readline
N = int(input())
A = sorted(list(map(int, input().split())), reverse=True)
# print(f'{A=}')
score = sum(A) - A[-1]

l = 0
r = N - 1
while True:
    r_score = A[r - 1]
    l_score = A[l + 1]
    if l_score > r_score:
        score += l_score - r_score
    else:
        break
    l += 1
    r -= 1
    if l >= r:
        break
print(score)

Submission status: Accepted

Solution code:
from collections import deque

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

A.sort(reverse=True)

comfort = 0
comfort_list = deque()

for a in A:
    if len(comfort_list) == 0:
        comfort_list.append(a)
    else:
        max_comfort = comfort_list.popleft()
        comfort += max_comfort
        comfort_list.append(min(a, max_comfort))
        comfort_list.append(min(a, max_comfort))

print(comfort)

Submission status: Accepted

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

Submission status: Accepted

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

def solve():
    cnt = 0
    ans = 0
    for i in range(N):
        c = 2 if i else 1
        for j in range(c):
            if cnt<N-1:
                ans += A[i]
            else:
                return ans
            cnt += 1
print(solve())

Submission status: Accepted

Solution code:
from collections import deque

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

d = deque()
d.append(A[1])
d.append(A[1])
ans = A[0]
for i in range(2, len(A)):
    ans += d.popleft()
    d.append(A[i])
    d.append(A[i])

print(ans)

Submission status: Accepted

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

Submission status: Accepted

Solution code:
import sys 
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
N = int(readline())
A = list(map(int,readline().split()))
A = sorted(A,reverse=True)
if N % 2 == 0: 
    k = N // 2
    ans = sum(A[:k])*2-A[0]
else:
    k = N // 2 + 1
    ans = sum(A[:k])*2-A[0]-A[k-1]
print(ans)

Submission status: Accepted

Solution code:
import heapq

def main():
    n = int(input())
    arr = list(map(int,input().split()))
    arr.sort()
    total = 0
    heap = []
    while arr:
        x = arr.pop()
        if not heap:
            heapq.heappush(heap,(-x,x,x))
        else:
            val,left,right = heapq.heappop(heap)
            val = abs(val)
            total += val
            heapq.heappush(heap,(-min(x,left),left,x))
            heapq.heappush(heap,(-min(x,right),x,right))
            #print(left,right,val)

    print(total)
        
    

main()

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
from collections import deque

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

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

comfort_queue = deque()
comfort_queue.append(A[0])

score=0
for i in range(1,N):
    comfort_queue.extend([A[i],A[i]])
    now_score = comfort_queue.popleft()
    score += now_score

print(score)

Submission status: Accepted

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

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

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

print(res)

Submission status: Accepted

Solution code:
import sys

sys.setrecursionlimit(1000000)

import bisect
import math
import collections
import heapq


def solve(N, As):
    As.sort()
    ans = []
    while len(ans) < N - 1:
        k = As.pop()
        if len(ans) == 0:
            ans.append(k)
        else:
            ans.append(k)
            ans.append(k)

    while len(ans) > N - 1:
        ans.pop()
    return sum(ans)

# solve(4, [2,2,1,3])
# solve(6, [1,2,3,4,5,6])
# solve(5, [1,2,3,4,5])

if __name__ == "__main__":
    N = int(input())
    As = list(map(int, input().split(" ")))
    print(solve(N, As))

Submission status: Accepted

Solution code:
# coding: utf-8


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

    ans = A[0]
    rest = N-2
    i = 1
    while rest > 0:
        if i == len(A):
            break

        if rest >= 2:
            ans += 2 * A[i]
            rest -= 2
        else:
            ans += A[i]
            rest -= 1
        i += 1

    return ans


print(main())

Submission status: Accepted

Solution code:
from collections import deque
N=int(input())
A=list(map(int, input().split()))

A=sorted(A, reverse=True)
if N==2:
    print(A[0])
    exit()

ans=A[0]+A[1]
que=deque([A[1], A[2],A[2]])
nowbin=1
for i in range(3,N):
    ans+=que.popleft()
    que.append(A[i])
    que.append(A[i])
    
print(ans)

Submission status: Accepted

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


def ni(): return int(ns())


def na(): return list(map(int, stdin.readline().split()))


def naa(N): return [na() for _ in range(N)]


def ns(): return stdin.readline().rstrip()  # ignore trailing spaces


N = ni()

a_array = na()

a_array.sort(reverse=True)

ans = a_array[0]

idx = 1

depth = 1

start = 1
end = 2

while(N - 1 > idx):
    start = 2 ** (depth-1)
    end = 2 ** depth
    if idx + 2 ** depth < N:
        ans += sum(a_array[start:end]) * 2
        idx = idx + 2 ** depth
    else:
        rest = (N - 1) - idx
        ans += sum(a_array[start:(start+rest//2)]) * 2
        ans += (rest % 2) * a_array[start+rest//2]
        idx = N - 1
    depth += 1
    # print(idx, ans)


print(ans)

Submission status: Accepted

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

Ali.sort(reverse=True)

p = sum(Ali[0:(N+1)//2])*2
p -= Ali[0]
if len(Ali)%2 == 1:
  p -= Ali[N//2]
  
print(p)

Submission status: Accepted

Solution code:
from collections import deque

n = int(input())
A = sorted(map(int, input().split()), reverse=True)
ans = 0
q = deque([A[0]])
for i in range(1, n):
    x = q.popleft()
    ans += x
    q.append(A[i])
    q.append(A[i])
print(ans)

Submission status: Accepted

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

if __name__ == '__main__':
    solve()

Submission status: Accepted

Solution code:
from heapq import *
import sys
from collections import *
from itertools import *
from decimal import *
import copy
from bisect import *
import math
sys.setrecursionlimit(4100000)
def gcd(a,b):
    if(a%b==0):return(b)
    return (gcd(b,a%b))
input=lambda :sys.stdin.readline().rstrip()
N=int(input())
A=list(map(int,input().split()))
A.sort()
X=A.pop()
N-=1
c=0
lst=deque()
count=1
while N:
    lst.append(A.pop())
    if count:
        count-=1
    else:
        X=lst.popleft()
        count=1
    c+=X
    N-=1
print(c)

Submission status: Accepted

Solution code:
from collections import deque
N = int(input())
A = list(map(int,input().rstrip().split(" ")))
A.sort(reverse = True)
ans = 0
que = deque()
que.append(A[0])
for i in range(1,len(A)):
    ans += que[0]
    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)

import heapq
heap=[a[0]*(-1)]

ans=0

for aa in a[1:]:
    tmp=heapq.heappop(heap)
    ans+=((-1)*tmp)
    heapq.heappush(heap,-1*aa)
    heapq.heappush(heap,-1*aa)

print(ans)

Submission status: Accepted

Solution code:
from sys import stdin, setrecursionlimit, stdout
#setrecursionlimit(1000000) #use "python" instead of "pypy" to avoid MLE
#from collections import deque
#from math import sqrt, floor, ceil, log, log2, log10, pi, gcd, sin, cos, asin
#from heapq import heapify, heappop, heappush, heapreplace, heappushpop
def ii(): return int(stdin.readline())
def fi(): return float(stdin.readline())
def mi(): return map(int, stdin.readline().split())
def fmi(): return map(float, stdin.readline().split())
def li(): return list(mi())
def si(): return stdin.readline().rstrip()
def lsi(): return list(si())
#mod=1000000007
res=['YES', 'NO']





test_case=1
while test_case:
    test_case-=1

    n=ii()
    a=li()
    a.sort()
    s=a[-1]
    i=n-2
    x=-1
    for j in range(n-2):
        s+=a[i]
        x+=1
        if x:
            x=-1
            i-=1
    print(s)

Submission status: Accepted

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

Submission status: Accepted

Solution code:
import sys
import math
import heapq
from collections import defaultdict, deque
from decimal import *
def r():
    return int(input())
def rm():
    return map(int,input().split())
def rl():
    return list(map(int,input().split()))

n=r()
a=rl()
a.sort(reverse=True)
b=[0,a[0]]
i=1
while len(b)<n and i<n:
    b.append(a[i])
    b.append(a[i])
    i+=1
print(sum(b[:n]))

Submission status: Accepted

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

A.sort(reverse=True)
result = 0

for i in range(1, N):
    n = i // 2
    result += A[n]

print(result)

Submission status: Accepted

Solution code:
#!/usr/bin/env python3

import sys
sys.setrecursionlimit(300000)


def solve(N: int, A: "List[int]"):
    A.sort(reverse=True)
    ret = 0
    #tmp = [A[0], A[1]]
    #for i in range(2, N):
    #    ret

    ret += A[0]
    cnt = 1
    i = 1
    while cnt < N - 1:
        #print(cnt, i, A[i])
        ret += A[i]
        cnt += 1
        if cnt % 2 == 1:
            i += 1
    print(ret)
    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))  # type: int
    A = [int(next(tokens)) for _ in range(N)]  # type: "List[int]"
    solve(N, A)

if __name__ == '__main__':
    main()

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

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

s=a[0]
t=n//2

s+=sum(a[1:t])*2
if n%2!=0:
    s+=a[t]


print(s)

Submission status: Accepted

Solution code:
import queue

n=int(input())

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

A.sort(reverse=True)

q=queue.Queue()

q.put(A[0])

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

print(ans)

Submission status: Accepted

Solution code:
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
n = int(readline())
a = list(map(int,readline().split()))
a.sort(reverse=True)

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

Submission status: Accepted

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

Submission status: Accepted

Solution code:
N = int(input())
K = sorted(map(int,input().split()),reverse=True)
A = []
for i in range(N-1):
    A.append(K[i+1])
    A.append(K[i])
B = sorted(A,reverse = True)
ans = sum(B[:N-1])
print(ans)

Submission status: Accepted

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

ls.sort()

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

print(ans)

Submission status: Accepted

Solution code:
n,*a=map(int,open(0).read().split())
a.sort()
ans=a.pop(-1)
n-=2
while n!=0:
    if n>1:
        ans+=a.pop(-1)*2
        n-=2
    if n==1:
        ans+=a.pop(-1)
        n-=1
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(2,len(a)):
    ans+=(a[(i)//2])
print(ans)

Submission status: Accepted

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

sm=lst[0]
sm+=2*sum(lst[1:n//2])
if n%2==1 : sm+=lst[n//2]

print(sm)

Submission status: Accepted

Solution code:
def main():

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

    A.sort(reverse = True)
    v = A[0]
    if N % 2 == 0:
        # print(v)
        v += sum(A[1:1+(N-2)//2]) * 2
        # print(v)
    else:
        v += sum(A[1:1+(N-2)//2]) * 2 + A[1+(N-2)//2]
    return v

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

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline
N = int(input())
A = list(map(int,input().split()))

A.sort(reverse=True)

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

Submission status: Accepted

Solution code:
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time,copy,functools
from collections import deque

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

DR = [1, -1, 0, 0]
DC = [0, 0, 1, -1]

def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def S(): return input()
     
def main():
    N = I()
    A = sorted(LI())[::-1]
    c = [A[0]]
    for x in A[1:]:
        c.append(x)
        c.append(x)
    ans= 0
    for i in range(len(c)):
        ans += c[i]
        if i == N - 2:
            break
    print(ans)

main()

Submission status: Accepted

Solution code:
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,tmp)
        
print(ans)

Submission status: Accepted

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

Submission status: Accepted

Solution code:
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#plsの隣使いきりカウント
scnt=0#2人行けるからそこのカウント

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

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

Solution code:
#dt = {} for i in x: dt[i] = dt.get(i,0)+1
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)

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

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