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:
def main():
    N = int(input())
    *A, = map(int, input().split())
    A.sort(reverse=True)

    cnt = 1
    ans = 0
    for x in A:
        if cnt == N: break
        if cnt == 1:
            ans += x
            cnt += 1
        else:
            if (use := N - cnt) >= 2:
                ans += x + x
                cnt += 2
            else:
                ans += x
                cnt += 1
                break
    print(ans)


if __name__ == '__main__':
    main()

# import sys
# input = sys.stdin.readline
# 
# sys.setrecursionlimit(10 ** 7)
# 
# (int(x)-1 for x in input().split())
# rstrip()
#
# def binary_search(*, ok, ng, func):
#     while abs(ok - ng) > 1:
#         mid = (ok + ng) // 2
#         if func(mid):
#             ok = mid
#         else:
#             ng = mid
#     return ok

Submission status: Accepted

Solution code:
from collections import deque
n=int(input())
a=sorted([int(i) for i in input().split()])[::-1]

if n==2:
    print(a[0])
else:
    b=deque([a[1],a[2]])
    ans=a[0]+a[1]
    minlist=[min(b)]
    j=1
    for i in range(n-3):
        if j==0:
            j+=1
            ans+=b[0]
            b+=[a[i+3]]
        else:
            j=0
            ans+=b[0]
            b.popleft()
            b+=[a[i+3]]

    print(ans)

Submission status: Accepted

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

A.sort(reverse=True)


score = A[0]
N -= 1

for i in A[1:]:
  N -= 1
  if(N==0):
    break
  score += i
  N -= 1
  if(N==0):
    break
  score += i
print(score)

Submission status: Accepted

Solution code:
import sys
read = sys.stdin.read
def main():
    n, *a = map(int, read().split())
    a.sort(reverse=True)
    r = a[0]
    end = int((n - 2) // 2)
    r += sum(a[1:end+1]) * 2
    if n % 2 == 1:
        r += a[end+1]
    print(r)

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
import sys
import math
from bisect import bisect_left
from bisect import bisect_right
from collections import defaultdict
from heapq import heappop, heappush
import itertools
import random
from collections import deque
from decimal import *
import queue

input = sys.stdin.readline

def inputInt(): return int(input())
def inputMap(): return map(int, input().split())
def inputList(): return list(map(int, input().split()))
def inputStr(): return input()[:-1]

inf = float('inf')
mod = 1000000007

#-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
#-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-

def main():
	N = inputInt()
	A = inputList()

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

	ansans = []
	pgt = queue.Queue()
	for i,val in enumerate(A):
		if i == 0:
			pgt.put(val)
		else:
			tmp = pgt.get()
			ansans.append(tmp)
			pgt.put(val)
			pgt.put(val)

	print(sum(ansans))


#-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
#-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
if __name__ == "__main__":
	main()

Submission status: Accepted

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


def solve(N: int, A: "List[int]"):
    A.sort(reverse=True)
    ans=0
    for i in range(N-1):
        ans+=A[(i+1)//2]
    print(ans)
    return


# Generated by 1.1.7.1 https://github.com/kyuridenamida/atcoder-tools  (tips: You use the default template now. You can remove this line by using your custom template)
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:
import heapq
from collections import deque
import sys
input = sys.stdin.readline
# sys.setrecursionlimit(100000)


def main():
    _ = int(input().strip())
    A_l = [-int(i) for i in input().strip().split()]
    heapq.heapify(A_l)

    used = deque()
    ans = 0
    # 初回と２回目は固定行動
    m1 = -1 * heapq.heappop(A_l)
    used.append(m1)
    m2 = -1 * heapq.heappop(A_l)
    used.append(m2)
    used.append(m2)
    ans += used.popleft()

    while A_l:
        m = -1 * heapq.heappop(A_l)
        used.append(m)
        used.append(m)
        ans += used.popleft()
    return ans


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

Submission status: Accepted

Solution code:
import heapq

n=int(input())
a=[-int(x) for x in input().split()]

a.sort()
ans=0
b=[]
heapq.heapify(b)

if n==2:
    ans-=a[0]
else:
    ans-=sum(a[:2])
    #間優先配列をつくる
    heapq.heappush(b,a[1])
    for i in range(2,n-1):
        #取る
        ans-=heapq.heappop(b)
        #増やす
        heapq.heappush(b,a[i])
        heapq.heappush(b,a[i])

print(ans)

Submission status: Accepted

Solution code:
from collections import deque
N = int(input())
K = list(sorted(map(int, input().split()), reverse=True))

max1 = K[0]
max2 = K[1]
if N == 2:
    print(max1)
else:
    max3 = K[2]
    count = max1 + max2
    cands = deque([max2, max3, max3])
    for k in K[3:]:
        cand = cands.popleft()
        count += cand
        cands.append(k)
        cands.append(k)
    print(count)

Submission status: Accepted

Solution code:
n = int(input())
arr = [int(n) for n in input().split()]

count = 0
arr.sort()
arr.reverse()
temp = arr.copy()
count +=arr[0]
arr.remove(max(arr))
x=n
n=n-2

if(n%2==0):
    for i in range(int(n/2)):
        count+=(2*arr[i])
    print(count)
else:
    for i in range(int((n-1)/2)):
        count+=(2*arr[i])
    count+=(temp[int(x/2)])
    print(count)

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

Solution code:
N=int(input())

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

B=sorted(A,reverse=True)

ans=B[0]

sheets=[B[0]]

ans=0
for i in range(1,N):

    ans += sheets[i-1]
    sheets.append(B[i])
    sheets.append(B[i])

print(ans)

Submission status: Accepted

Solution code:
import sys

def II(): return int(input())
def MI(): return map(int,input().split())
def LI(): return list(map(int,input().split()))
def TI(): return tuple(map(int,input().split()))
def RN(N): return [input().strip() for i in range(N)]


def main():
    N = II()
    A = LI()
    As = sorted(A, reverse=True)
    ans = 0

    for i in range(N):
        j = i//2
        if i != 0:
            ans += As[j]
    
    print(ans)

if __name__ == "__main__":
	main()

Submission status: Accepted

Solution code:
# 2020/07/05
# AtCoder Beginner Contest 173 - D

# Input
n = int(input())
a = list(map(int,input().split()))

# Calc
a.sort()
a.reverse()

ans = a[0]
idx = 1
for i in range(2, n):
    ans = ans + a[idx]
    if i % 2 != 0:
        idx = idx + 1
        
# Output
print(ans)

Submission status: Accepted

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

if N % 2 == 0:
  k = N // 2
  print(A_list[0] + 2*sum(A_list[1:k]))
else:
  k = N // 2
  print(A_list[0] + 2*sum(A_list[1:k]) + A_list[k])

Submission status: Accepted

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

a.sort(reverse=True)

point = a[0]

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

if n%2 == 1:
    point += a[i+1]

print(point)

Submission status: Accepted

Solution code:
N = int(input())
A = list(map(int, input().split()))
A = sorted(A, reverse=True)
ans = A[0]

t = N
if N % 2 == 1:
    t = N + 1
for i in range((t-2)//2):
    ans += 2*A[i+1]
if N % 2 == 1:
    ans -= A[i+1]

print(ans)

Submission status: Accepted

Solution code:
num = (int)(input())
a = sorted(list(map(int, input().split(" "))), reverse=True)
b = [a[0]]
total = a[0]
for i in range(3, num + 1):
    total += a[(i - 1) // 2]
print(total)

Submission status: Accepted

Solution code:
import math
n = int(input())
a = list(map(int, input().split()))
list.sort(a, reverse = True)
c = math.ceil(n/2)
b = [2]*c + [0]*(n-c)    

b[0] -= 1
if n%2 == 1:
    b[c-1] -= 1

ans = 0
for i in range(n):
    ans += b[i]*a[i]
print(ans)

Submission status: Accepted

Solution code:
def main():
    n = int(input())
    A = list(map(int,input().split()))

    A.sort(reverse = True)

    # print(A)
    B = [A[0]]
    for i in A[1:]:
        B.append(i)
        B.append(i)

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


main()

Submission status: Accepted

Solution code:
import queue

N = int(input())

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

S.sort(reverse = True)

#print(S)

q = queue.Queue()
q.put(S[0])

ans = 0

for i in range(1, N):
    ans += q.get()
    #print(ans)
    q.put(S[i])
    q.put(S[i])

print(ans)

Submission status: Accepted

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

Submission status: Accepted

Solution code:
import heapq
def main():
    n = int(input())
    a = list(map(int,input().split()))
    a.sort()
    heap = []
    heapq.heappush(heap,-a.pop())
    total = 0
    while a:
        score = -heapq.heappop(heap)
        total += score
        temp = -a.pop()
        heapq.heappush(heap,temp)
        heapq.heappush(heap,temp)
    print(total)



if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import sys

def main():

    input = sys.stdin.readline

    N = int(input())
    A = sorted(list(map(int,input().split())))[::-1]

    ans = A[0]

    count = 2

    if count >= N:
        print(ans)
        return


    for i in range(1,N):
        count += 1
        ans += A[i]

        if count >= N:
            break

        count += 1
        ans += A[i]

        if count >= N:
            break

    print(ans)

if __name__ == "__main__":
    main()

Submission status: Accepted

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

from collections import deque

input()
A = input().split(' ')
A = list(map(int, A))
A = sorted(A)[::-1]

d = deque()

ret = 0

for a in A:
    if len(d) == 0:
        d.append(a)
    else:
        ret += d.popleft()
        d.append(a)
        d.append(a)

print(ret)

Submission status: Accepted

Solution code:
from collections import deque

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

A.sort(reverse=True)
ans = 0

point = deque()
point.append(A.pop(0))
for i in A:
    ans += point.popleft()
    point.append(i)
    point.append(i)

print(ans)

Submission status: Accepted

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

Submission status: Accepted

Solution code:
import sys
import heapq
input = lambda: sys.stdin.readline().rstrip()
n = int(input())
a = [int(i) for i in input().split()]
a.sort()
hl = [a[-1] * -1]
a.pop()
# a = a[::-1]

heapq.heapify(hl)
ans = 0

while (a):
    now = a.pop()
    ans += heapq.heappop(hl) * (-1)
    for i in range(2):
        heapq.heappush(hl, now * -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(n-2):
    ans += A[(i//2) + 1]

print(ans)

Submission status: Accepted

Solution code:
import sys
import numpy as np
import random
from decimal import Decimal
import itertools
import re
import bisect
from collections import deque, Counter
from functools import lru_cache
from numba import jit

sys.setrecursionlimit(10**9)
INF = 10**13
def LI(): return list(map(int, sys.stdin.buffer.readline().split()))
def I(): return int(sys.stdin.buffer.readline())
def LS(): return sys.stdin.buffer.readline().rstrip().decode('utf-8').split()
def S(): return sys.stdin.buffer.readline().rstrip().decode('utf-8')
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)]
def SRL(n): return [list(S()) for i in range(n)]
def MSRL(n): return [[int(j) for j in list(S())] for i in range(n)]
def SERIES(n): return np.fromstring(sys.stdin.buffer.read(), dtype=np.int32, sep=' ')
def GRID(h,w): return np.fromstring(sys.stdin.buffer.read(), dtype=np.int32, sep=' ').reshape(h,-1)[:,:w]
def GRIDfromString(h,w): return np.frombuffer(sys.stdin.buffer.read(), 'S1').reshape(h,-1)[:,:w]
MOD = 1000000007

def main():
	n = I()
	a_list = LI()
	a_list.sort()
	ans = a_list[-1]
	if n % 2 == 0:
		for i in range(1,(n-2)//2+1):
			ans += a_list[-1-i]*2
	else:
		for i in range(1,(n-3)//2+1):
			ans += a_list[-1-i]*2
		ans += a_list[-1-(n-3)//2-1]
	print(ans)


if __name__ == '__main__':
    main()

Submission status: Accepted

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

confortability = sorted(A,reverse=True)
neighbours = 0
idx = 0
ans = 0
for i, conf in enumerate(confortability):
    if i == 0:
        continue
    if neighbours < 1:
        ans += confortability[idx]
        neighbours += 1
    else:
        idx += 1
        ans += confortability[idx]
        neighbours = 0

print(ans)

Submission status: Accepted

Solution code:


def resolve():
    import sys
    input = sys.stdin.readline
    n = int(input().rstrip())
    a_list = [int(x) for x in input().rstrip().split(" ")]
    a_list.sort(reverse=True)
        
    from heapq import heappush, heappop

    hq = []
    joined = set()
    joined.add(0)
    heappush(hq, (-a_list[0], 0, 0))
    result = 0
            
    for i in range(1, n):

        comfort, left, right = heappop(hq)
        comfort = -comfort

        result += comfort

        heappush(hq, (-(a_list[left] if a_list[left] < a_list[i] else a_list[i]),left, i))
        heappush(hq, (-(a_list[right] if a_list[right] < a_list[i] else a_list[i]),i,right))
    
    print(result)


if __name__ == "__main__":
    resolve()


# を理解する。そうすると、明らかに制限時間内に実行が終わらないソースコードを出さなくなる。ちなみに、競プロでは 108108 ～ 109109 回程度のループが回せるといわれている。

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:
    mat=N//2
    for i in range(mat-1):
        ans+=2*A[1+i]
else:
    mat=(N-1)//2
    for j in range(mat-1):
        ans+=2*A[1+j]
    ans+=A[mat]
print(ans)

Submission status: Accepted

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

half = (N+1)//2
A.sort(reverse = True)

ans = sum(A[:(half-1)])

if (N-half) != half:
    ans += sum(A[1:half])
else:
    ans += sum(A[1:half]) + A[half-1]

print(ans)

Submission status: Accepted

Solution code:
n = int(input())
a=list(map(int,input().split()))
b = sorted(a)
b = b[::-1]
x = 0
y = 0
for i in range(n):
    y += x
    x = b[int(i / 2 + 0.5)]
print(y)

Submission status: Accepted

Solution code:
import sys
from io import StringIO
import unittest
import os
import heapq

# 再帰処理上限(dfs作成時に設定するのが面倒なので限度近い値を組み込む)
sys.setrecursionlimit(999999999)


# 実装を行う関数
def resolve(test_def_name=""):
    n = int(input())
    a_s = list(map(int, input().split()))

    a_s.sort(reverse=True)

    que = []
    heapq.heapify(que)

    ans = 0
    for cnt, a in enumerate(a_s):
        a = -a
        if cnt == 0:
            heapq.heappush(que, a)
            continue

            # キューから値の取り出し
        target = heapq.heappop(que)
        ans += -target
        heapq.heappush(que, a)
        heapq.heappush(que, a)

    print(ans)


# テストクラス
class TestClass(unittest.TestCase):
    def assertIO(self, assert_input, output):
        stdout, sat_in = sys.stdout, sys.stdin
        sys.stdout, sys.stdin = StringIO(), StringIO(assert_input)
        resolve(sys._getframe().f_back.f_code.co_name)
        sys.stdout.seek(0)
        out = sys.stdout.read()[:-1]
        sys.stdout, sys.stdin = stdout, sat_in
        self.assertEqual(out, output)

    def test_input_1(self):
        test_input = """4
2 2 1 3"""
        output = """7"""
        self.assertIO(test_input, output)

    def test_input_2(self):
        test_input = """7
1 1 1 1 1 1 1"""
        output = """6"""
        self.assertIO(test_input, output)

    # 自作テストパターンのひな形(利用時は「tes_t」のアンダーバーを削除すること
    def test_1original_1(self):
        test_input = """4
2 2 3 3"""
        output = """9"""
        self.assertIO(test_input, output)


# 実装orテストの呼び出し
if __name__ == "__main__":
    if os.environ.get("USERNAME") is None:
        # AtCoder提出時の場合
        resolve()

    else:
        # 自PCの場合
        unittest.main()

Submission status: Accepted

Solution code:
def input_int():
    return map(int, input().split())

def one_int():
    return int(input())

def one_str():
    return input()

def many_int():
    return list(map(int, input().split()))

import heapq

N=one_int()
A=many_int()

sort_A = sorted(A,reverse=True)



sukima = [-sort_A[0]]
heapq.heapify(sukima)

sort_A = sort_A[1:]
sums = 0
for a in sort_A:
    sums += heapq.heappop(sukima)
    heapq.heappush(sukima, -a)
    heapq.heappush(sukima, -a)

print(-sums)

Submission status: Accepted

Solution code:
N = int(input())
S = list(map(int,input().split()))
rev_sorted_S = list(reversed(sorted(S)))

ans = 0
for n in range(1,N):
  if n == 1:
    ans += max(S)
  else:
    ans += rev_sorted_S[n//2]
print(ans)

Submission status: Accepted

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

Submission status: Accepted

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

resolve()

Submission status: Accepted

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

counter = 0
idx = 1
for _ in range(N-2):
  ans += A[idx]
  counter += 1
  if counter == 2:
    idx += 1
    counter = 0
print(ans)

Submission status: Accepted

Solution code:
n = int(input())
a = sorted(list(map(int,input().split())))
cou = a.pop()
n1 = n-2
if n1%2==0:
  t = n1//2
  for i in range(t):
    q = a.pop()
    cou += q*2
else:
  t = n1//2
  for i in range(t):
    q = a.pop()
    cou += 2*q
  cou += a.pop()
print(cou)

Submission status: Accepted

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

print(ans)

Submission status: Accepted

Solution code:
import heapq

N = int(input())
A = list(map(int, input().split()))
A = list(map(lambda x: x * (-1), A))

heapq.heapify(A)

ans = 0
N -= 2
ans += heapq.heappop(A) * (-1)

if N == 0:
    print(ans)
    exit()
elif N == 1:
    ans += A[0]
    print(ans)
    exit()
elif N >= 2:
    q = N // 2
    r = N % 2
    for i in range(1, q + 1):
        ans += 2 * heapq.heappop(A) * (-1)
    if r == 1:
        ans += heapq.heappop(A) * (-1)
    print(ans)

Submission status: Accepted

Solution code:
def main1():
    N=int(input())
    A=list(map(int,input().split()))
    A.sort(reverse=True)
    cn=1
    ans=A[0]
    tmp=0
    if N%2==0:
        while cn<-(-N//2):
            ans+=A[cn]*2
            cn=cn+1
        print(ans)
    else:
        while cn<-(-N//2)-1:
            ans+=A[cn]*2
            cn=cn+1
        print(ans+A[cn])
main1()

Submission status: Accepted

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

a.sort(reverse = True)

ans = 0

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

print(ans)

Submission status: Accepted

Solution code:
N=int(input())
A=list(map(int,input().split()))
import heapq
A=[-i for i in A]
heapq.heapify(A)
x=heapq.heappop(A)
ans=0
ans+=-x
l=0
if N==2:
    print(ans)
else:
    while True:
        x=heapq.heappop(A)
        ans+=-x
        l+=1
        if l==N-2:
            break
        ans+=-x
        l+=1
        if l==N-2:
            break
    print(ans)

Submission status: Accepted

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

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

Submission status: Accepted

Solution code:
n = int(input())

num = n - 2

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

a = sorted(a, reverse=True)

ans = a[0]
t = 1
while num > 0:
    if num >=2 :
        ans += a[t]*2
        t +=1
        num -= 2
    else :
        ans += a[t]
        num -=1

print(ans)

Submission status: Accepted

Solution code:
from collections import deque

n = int(input())
a = [int(e) for e in input().split()]

a.sort()

total = 0
q = deque()
q.append(a[n -1])
for i in reversed(range(n - 1)):
    q.append(a[i])
    q.append(a[i])
    total += q.popleft()

print(total)

Submission status: Accepted

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

Submission status: Accepted

Solution code:
n=int(input())
seq=list(map(int,input().split()))
seq.sort()
t=n//2
s=seq[t:]
if 1==1:
        x=seq[-1]
        d=sum(s)-x
        d=d*2
        d+=x
        
        if n%2==0:
                print(d)
        else:
                print(d-seq[t])

Submission status: Accepted

Solution code:
N=int(input())
a=input().split()
A=[int(b) for b in a]
AS=sorted(A,reverse=True)
N=len(AS)
NN=N//2
if N%2==0:
    answer = 0
    answer += AS[0]
    answer += sum(AS[1:NN]) * 2
    print(answer)
else:
    answer=0
    answer+=AS[0]
    answer += sum(AS[1:NN]) * 2
    answer+=AS[NN]
    print(answer)

Submission status: Accepted

Solution code:
N=int(input())
S=list(map(int,input().split()))
S.sort()
S.reverse()
tmp=0
ans=0
if len(S)==2:
    print(S[0])
    
else:
    ans+=S[0]

    if (N-2)%2==0:
        for i in range((N-2)//2):
            ans+=S[i+1]*2
        #print("mohu1")    
        print(ans)
    else:
        for i in range((N-2)//2):
            
            ans+=S[i+1]*2
            tmp=i+1
        #print("mohu")
        print(ans+S[tmp+1])

Submission status: Accepted

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

box = sorted(box, reverse=True)
li = [box[0]]
for b in box[1:]:
    li.append(b)
    li.append(b)

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

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-

#############
# Libraries #
#############

import sys
input = sys.stdin.readline

import math
#from math import gcd
import bisect
import heapq
from collections import defaultdict
from collections import deque
from collections import Counter
from functools import lru_cache

#############
# Constants #
#############

MOD = 10**9+7
INF = float('inf')
AZ = "abcdefghijklmnopqrstuvwxyz"

#############
# Functions #
#############

######INPUT######
def I(): return int(input().strip())
def S(): return input().strip()
def IL(): return list(map(int,input().split()))
def SL(): return list(map(str,input().split()))
def ILs(n): return list(int(input()) for _ in range(n))
def SLs(n): return list(input().strip() for _ in range(n))
def ILL(n): return [list(map(int, input().split())) for _ in range(n)]
def SLL(n): return [list(map(str, input().split())) for _ in range(n)]

######OUTPUT######
def P(arg): print(arg); return
def Y(): print("Yes"); return
def N(): print("No"); return
def E(): exit()
def PE(arg): print(arg); exit()
def YE(): print("Yes"); exit()
def NE(): print("No"); exit()

#####Shorten#####
def DD(arg): return defaultdict(arg)

#####Inverse#####
def inv(n): return pow(n, MOD-2, MOD)

######Combination######
kaijo_memo = []
def kaijo(n):
  if(len(kaijo_memo) > n): return kaijo_memo[n]
  if(len(kaijo_memo) == 0): kaijo_memo.append(1)
  while(len(kaijo_memo) <= n): kaijo_memo.append(kaijo_memo[-1] * len(kaijo_memo) % MOD)
  return kaijo_memo[n]

gyaku_kaijo_memo = []
def gyaku_kaijo(n):
  if(len(gyaku_kaijo_memo) > n): return gyaku_kaijo_memo[n]
  if(len(gyaku_kaijo_memo) == 0): gyaku_kaijo_memo.append(1)
  while(len(gyaku_kaijo_memo) <= n): gyaku_kaijo_memo.append(gyaku_kaijo_memo[-1] * pow(len(gyaku_kaijo_memo),MOD-2,MOD) % MOD)
  return gyaku_kaijo_memo[n]

def nCr(n,r):
  if n == r: return 1
  if n < r or r < 0: return 0
  ret = 1
  ret = ret * kaijo(n) % MOD
  ret = ret * gyaku_kaijo(r) % MOD
  ret = ret * gyaku_kaijo(n-r) % MOD
  return ret

######Factorization######
def factorization(n):
  arr = []
  temp = n
  for i in range(2, int(-(-n**0.5//1))+1):
    if temp%i==0:
      cnt=0
      while temp%i==0: 
        cnt+=1 
        temp //= i
      arr.append([i, cnt])
  if temp!=1: arr.append([temp, 1])
  if arr==[]: arr.append([n, 1])
  return arr

#####MakeDivisors######
def make_divisors(n):
  divisors = []
  for i in range(1, int(n**0.5)+1):
    if n % i == 0:
      divisors.append(i)
      if i != n // i: 
        divisors.append(n//i)
  return divisors

#####MakePrimes######
def make_primes(N):
  max = int(math.sqrt(N))
  seachList = [i for i in range(2,N+1)]
  primeNum = []
  while seachList[0] <= max:
    primeNum.append(seachList[0])
    tmp = seachList[0]
    seachList = [i for i in seachList if i % tmp != 0]
  primeNum.extend(seachList)
  return primeNum

#####GCD#####
def gcd(a, b):
    while b: a, b = b, a % b
    return a

#####LCM#####
def lcm(a, b):
    return a * b // gcd (a, b)

#####BitCount#####
def count_bit(n):
  count = 0
  while n:
    n &= n-1
    count += 1
  return count

#####ChangeBase#####
def base_10_to_n(X, n):
  if X//n: return base_10_to_n(X//n, n)+[X%n]
  return [X%n]

def base_n_to_10(X, n):
  return sum(int(str(X)[-i-1])*n**i for i in range(len(str(X))))

def base_10_to_n_without_0(X, n):
  X -= 1
  if X//n: return base_10_to_n_without_0(X//n, n)+[X%n]
  return [X%n]

#####IntLog#####
def int_log(n, a):
  count = 0
  while n>=a:
    n //= a
    count += 1
  return count

#############
# Main Code #
#############

N = I()
A = IL()
A.sort(reverse=True)

q = [-A[1],-A[1]]
ans = A[0]
for a in A[2:]:
  ans -= q[0]
  heapq.heappop(q)
  heapq.heappush(q,-a)
  heapq.heappush(q,-a)
print(ans)

Submission status: Accepted

Solution code:
n =int(input())
kotae=0
a = input().split(" ")
lint_a = [int(n) for n in a]
lista = sorted(lint_a, reverse = True)
if n%2==0:
  kotae+=lista[0]
  b=n//2+1
  for i in range(1,b-1):
    kotae+=lista[i]*2
else:
  kotae+=lista[0]
  b=(n+1)//2
  kotae+=lista[b-1]
  for i in range(1,b-1):
    kotae+=lista[i]*2
print(kotae)

Submission status: Accepted

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

Submission status: Accepted

Solution code:
from collections import deque

def main(N, A):
    # 席順
    l = A[:2]
    # 心地よさ合計
    ans = A[0]

    d = deque([A[1], A[1]])

    for a in A[2:]:
        ans += d.popleft()
        d.extend([a, a])
    print(ans)



if __name__ == '__main__':
    N = int(input())
    A = list(map(int, input().split()))
    A.sort(reverse = True)
    main(N, A)

Submission status: Accepted

Solution code:
from heapq import*


n = int(input())
A = sorted([-int(x) for x in input().split()], reverse = True)

B = []
a = A.pop()
heappush(B, a)

ans = 0
while A:
    a = A.pop()
    b = heappop(B)
    ans += -b
    heappush(B, a); heappush(B, a)

print(ans)

Submission status: Accepted

Solution code:
N = int(input())

nums = sorted([int(i) for i in input().split()], reverse=True)

cnt = 0
for i, v in enumerate(nums):
    if i != 0:
        cnt += nums[i//2]
        
print(cnt)

Submission status: Accepted

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

if N == 0:
    ans = 0
elif N == 1:
    ans = A[0]
else:
    ans = A[0]
    u = 1
    for i in range(2,N):
        ans += A[u]
        if i % 2 != 0:
            u += 1

print(ans)

Submission status: Accepted

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

alist.sort(reverse=True)
counter = 0
for i in range(n):
    if i == 0:
        counter += 0
    else:
        counter += alist[i//2]
print(counter)

Submission status: Accepted

Solution code:
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines

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

a2 = sorted((a + a), reverse=True)
a2[0] = 0


print(sum(a2[:n:]))

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

for i in range(1, n):
    x = d.popleft()
    ans += x
    d.append(a[i])
    d.append(a[i])

print(ans)