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

Submission status: Accepted

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

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
"""
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)

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
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))  # 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:
"""
    Satwik_Tiwari ;) .
    4th july , 2020  - Saturday
"""

#===============================================================================================
#importing some useful libraries.
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  # Counter(list)  return a dict with {key: count}
from itertools import combinations as comb # if a = [1,2,3] then print(list(comb(a,2))) -----> [(1, 2), (1, 3), (2, 3)]
from itertools import permutations as permutate
from bisect import bisect_left as bl
#If the element is already present in the list,
# the left most position where element has to be inserted is returned.
from bisect import bisect_right as br
from bisect import bisect
#If the element is already present in the list,
# the right most position where element has to be inserted is returned

#==============================================================================================

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)

# inp = lambda: sys.stdin.readline().rstrip("\r\n")

#===============================================================================================
#some shortcuts

mod = 1000000007
def inp(): return sys.stdin.readline().rstrip("\r\n") #for fast input
def out(var): sys.stdout.write(str(var))  #for fast output, always take string
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 graph(vertex): return [[] for i in range(0,vertex+1)]
def zerolist(n): return [0]*n
def nextline(): out("\n")  #as stdout.write always print sring.
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) : # Check Prime Number or not
    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

#===============================================================================================
# code here ;))
def bs(a,l,h,x):
    while(l<h):
        # print(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): #O(n loglogn) nearly linear
    #all odd mark 1
    for i in range(3,((10**6)+1),2):
        a[i] = 1
    #marking multiples of i form i*i 0. they are nt prime
    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 #special left case
    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)
# testcase(int(inp()))

Submission status: Accepted

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

a.sort(reverse=True)
cnt = 1
ans = a[0]
for ai in a[1:]:
    if cnt + 2 >= n-1:
        ans += ai * (n-1-cnt)
        break
    ans += 2 * ai
    cnt += 2

print(ans)

Submission status: Accepted

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

Submission status: Accepted

Solution code:
#!python3

import sys
iim = lambda: map(int, sys.stdin.readline().rstrip().split())

def resolve():
    it = map(int, sys.stdin.read().split())
    N = next(it)
    A = list(it)

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

    print(ans)

if __name__ == "__main__":
    resolve()

Submission status: Accepted

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

A.sort()
A.reverse()

list = []
ans = 0
list.append(A[0])
for i in range(1, len(A)):
        ans += list[i - 1]
        list.append(A[i])
        list.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
ind = 0
for i in range(N-1):
    if i == 0:
        ans += A[ind]
        ind += 1
    elif i % 2 == 1:
        ans += A[ind]
    else:
        ans += A[ind]
        ind += 1

print(ans)

Submission status: Accepted

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

Submission status: Accepted

Solution code:
N = int(input())
FRI_STRING=input().split()
FRI = [int(s) for s in FRI_STRING]
 
import numpy as np
ARR = np.array(FRI)
ARR = np.sort(ARR)
ARR = ARR[::-1]
 
count = 0
sum = 0
for i in range(len(FRI)-1):
  #print(ARR[count])
  sum = sum + ARR[count]
  if i % 2 == 0:
    count = count + 1
  
    
print(sum)

Submission status: Accepted

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

Submission status: Accepted

Solution code:
def main():
    n  = int(input())
    a = [int(i) for i in input().split()]
    a.sort()
    ans = 0
    for i in range(1,n):
        ans += a[n-1-(i//2)]
    print(ans)

main()

Submission status: Accepted

Solution code:
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-1-(math.ceil(i/2))]
print(ans)

Submission status: Accepted

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

class MM:
    def __init__(self, c_max, c_cnt):
        self.c_max = c_max
        self.c_cnt = c_cnt

def solve(N: int, A: "List[int]"):
    sl = list(reversed(sorted(A)))
    score = 0
    c_max = sl[0]
    h = {sl[0]: 1}
    queue = deque()
    queue.append(c_max)
    for i in range(1, len(sl)):
        score += c_max

        h[c_max] -= 1
        if sl[i] in h:
            h[sl[i]] += 2
        else:
            h[sl[i]] = 2
            queue.append(sl[i])

        if h[c_max] == 0:
            queue.popleft()
            c_max = queue[0]
        # print(f'{i} {sl[i]} {c_max} {h}')
    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))  # 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 sys
import math
# sys.stdin=open('input.txt','r')
# sys.stdout=open('output2.txt','w')
from sys import stdin,stdout
from collections import deque,defaultdict
from math import ceil,floor,inf,sqrt,factorial,gcd,log2
from copy import deepcopy
ii1=lambda:int(stdin.readline().strip())
is1=lambda:stdin.readline().strip()
iia=lambda:list(map(int,stdin.readline().strip().split()))
isa=lambda:stdin.readline().strip().split()
mod=1000000007

n=ii1()
arr=iia()
ans=0
arr.sort(reverse=True)
for i in range(1,n):
    ans+=arr[i//2]
print(ans)

Submission status: Accepted

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

Submission status: Accepted

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

class MM:
    def __init__(self, c_max, c_cnt):
        self.c_max = c_max
        self.c_cnt = c_cnt

def solve(N: int, A: "List[int]"):
    sl = list(reversed(sorted(A)))
    score = 0
    c_max = sl[0]
    h = {sl[0]: 1}
    queue = deque()
    queue.append(c_max)
    for i in range(1, len(sl)):
        score += c_max

        if c_max == sl[i]:
            h[c_max] += 1
        else:
            h[c_max] -= 1
            if sl[i] in h:
                h[sl[i]] += 2
            else:
                h[sl[i]] = 2
                queue.append(sl[i])

            if h[c_max] == 0:
                queue.popleft()
                c_max = queue[0]
        # print(f'{i} {sl[i]} {c_max} {h}')
    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))  # 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:
#!/usr/bin/env python3
n, *a = map(int, open(0).read().split())
list.sort(a, reverse=True)
ans = a[0]
for i in range((n-1)//2):
    ans += a[i+1]*2
if n % 2 == 1:
    ans -= a[i+1]
print(ans)

Submission status: Accepted

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

N = int(input())
A = [int(s) for s in input().split()]
A_s = zip(list(range(N)), A)
A_s = sorted(A_s, key=lambda x: x[1], reverse=True)

kokoti = 0
kokoti += A_s[0][1]

#h = list(map(lambda x: (-1*x[0], x[1]), A_s))
h = []
heapq.heapify(h)  # リストを優先度付きキューへ
heapq.heappush(h, (-A_s[1][1]))
heapq.heappush(h, (-A_s[1][1]))

for i in range(2, N):
    x = heapq.heappop(h)  # 最大値の取り出し
    kokoti += (-x)
    #heapq.heappush(h, (-A_s[i][1], (a[0], A_s[i][0])))  # 要素の挿入
    #heapq.heappush(h, (-A_s[i][1], (A_s[i][0], a[1])))
    heapq.heappush(h, (-A_s[i][1]))  # 要素の挿入
    heapq.heappush(h, (-A_s[i][1]))

print(kokoti)

Submission status: Accepted

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

ans = 0
A.sort(reverse=True)
#print(A)
from collections import deque
d = deque(A)
for i in range(1,N):
    if i == 1:
        ans += d.popleft()
        continue
    if i % 2 == 0:
        ans += d[0]
    else:
        ans += d.popleft()
#print(A)
print(ans)

Submission status: Accepted

Solution code:
N = int(input())
A = list(map(int,input().split()))
A_new = sorted(A, reverse=True)
A_feel = []
sum = 0
for i in range(N):
  if A_feel == []:
    count = 1
  else:
    count = 2
  for j in range(count):
    A_feel.append(A_new[i])

for i in range(N-1):
  sum += A_feel[i]
  
print(sum)

Submission status: Accepted

Solution code:
from collections import deque


def main():
    input()  # n
    friendliness = deque(sorted(int(x) for x in input().split()))
    edges = deque()
    popped = friendliness.pop()
    edges.append(popped)
    ans = 0
    while friendliness:
        ans += edges.popleft()
        popped = friendliness.pop()
        edges.append(popped)
        edges.append(popped)
    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]
if n >2:
    for i in range(2,n,1):
        j = i//2
        ans += a[j]

print (ans)

Submission status: Accepted

Solution code:
import sys
import itertools


def resolve(in_):
    n = int(in_.readline())
    a = list(map(int, in_.readline().split()))
    assert len(a) == n
    a.sort(reverse=True)
    ans = a[0]
    ans += sum(itertools.islice(itertools.chain.from_iterable((x, x) for x in a[1:]), n - 2))

    return ans


def main():
    answer = resolve(sys.stdin.buffer)
    print(answer)


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
from collections import deque


def main():
    input()  # n
    friendliness = [int(x) for x in input().split()]
    friendliness.sort()
    friendliness = deque(friendliness)
    edges = deque()
    popped = friendliness.pop()
    edges.append(popped)
    ans = 0
    while friendliness:
        ans += edges.popleft()
        popped = friendliness.pop()
        edges.append(popped)
        edges.append(popped)
    print(ans)


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(1 << 25)
read = sys.stdin.readline
ra = range
enu = enumerate


def exit(*argv, **kwarg):
    print(*argv, **kwarg)
    sys.exit()


def mina(*argv, sub=1): return list(map(lambda x: x - sub, argv))
# 受け渡されたすべての要素からsubだけ引く.リストを*をつけて展開しておくこと


def a_int(): return int(read())


def ints(): return list(map(int, read().split()))


def read_col(H):
    '''H is number of rows
    A列、B列が与えられるようなとき
    ex1)A,B=read_col(H)    ex2) A,=read_col(H) #一列の場合'''
    ret = []
    for _ in range(H):
        ret.append(list(map(int, read().split())))
    return tuple(map(list, zip(*ret)))


def read_tuple(H):
    '''H is number of rows'''
    ret = []
    for _ in range(H):
        ret.append(tuple(map(int, read().split())))
    return ret


def read_matrix(H):
    '''H is number of rows'''
    ret = []
    for _ in range(H):
        ret.append(list(map(int, read().split())))
    return ret
    # return [list(map(int, read().split())) for _ in range(H)] # 内包表記はpypyでは遅いため


MOD = 10**9 + 7
INF = 2**31  # 2147483648 > 10**9
# default import
from collections import defaultdict, Counter, deque
from operator import itemgetter, xor, add
from itertools import product, permutations, combinations
from bisect import bisect_left, bisect_right  # , insort_left, insort_right
from functools import reduce
from math import gcd


def lcm(a, b):
    # 最小公倍数
    g = gcd(a, b)
    return a // g * b

# 貪欲に大きい方だと思うんだけど違うのかな
# 貪欲でない反例 (わからん)


N = a_int()
A = ints()
A.sort()
ans = A.pop()
N -= 2
while N > 1:
    N -= 2
    ans += 2 * A.pop()
if N == 1:
    ans += A.pop()
print(ans)

Submission status: Accepted

Solution code:
n = int(input())
a = list(map(int, input().split(' ')))
 
def merge_sort(arr):
    if len(arr) <= 1:
        return arr
 
    mid = len(arr) // 2
    # ここで分割を行う
    left = arr[:mid]
    right = arr[mid:]
 
    # 再帰的に分割を行う
    left = merge_sort(left)
    right = merge_sort(right)
 
    # returnが返ってきたら、結合を行い、結合したものを次に渡す
    return merge(left, right)
 
 
def merge(left, right):
    merged = []
    l_i, r_i = 0, 0
 
    # ソート済み配列をマージするため、それぞれ左から見ていくだけで良い
    while l_i < len(left) and r_i < len(right):
        # ここで=をつけることで安定性を保っている
        if left[l_i] >= right[r_i]:
            merged.append(left[l_i])
            l_i += 1
        else:
            merged.append(right[r_i])
            r_i += 1
 
    # 上のwhile文のどちらかがFalseになった場合終了するため、あまりをextendする
    if l_i < len(left):
        merged.extend(left[l_i:])
    if r_i < len(right):
        merged.extend(right[r_i:])
    return merged
 
s = merge_sort(a)
ans=s[0]
for i in range(1,n//2):
    ans += s[i]*2
if n%2 == 1:
    ans += s[n//2]
 
print(ans)

Submission status: Accepted

Solution code:
from collections import deque


def main():
    n = int(input())  # n
    friendliness = [int(x) for x in input().split()]
    friendliness.sort()
    friendliness = deque(friendliness)
    edges = deque()
    popped = friendliness.pop()
    edges.append(popped)
    ans = 0
    counter = 0
    while friendliness:
        ans += edges.popleft()
        counter += 1
        popped = friendliness.pop()
        edges.append(popped)
        edges.append(popped)
    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 = 0
for i in range(1, N):
    ans += A[i // 2]
print(ans)

Submission status: Accepted

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

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

A.sort(reverse=True)
#print(A)

"""
ans = 0
list = []
for i in range(N):
  if ( i==0 ) :
    list.append(A[0])
  else:
    max_index = list.index(max(list))
    ans += list[max_index]
    list[max_index] = A[i]
    list.insert(max_index, A[i])
  #print(list,ans)
"""

ans = 0
for i in range(N):
  if ( i==0 ) :
    ans += 0
  else:
    ans += A[i//2]

print(ans)

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-1):
    ans += b[(i+1)//2]
print(ans)

Submission status: Accepted

Solution code:
from sys import stdin
N = int(stdin.readline().rstrip())
ran = [int(x) for x in stdin.readline().rstrip().split()]
ran.sort(reverse=True)

gen = len(ran) - 2
goukei = ran[0]
if gen % 2 == 0:
  for i in range(int(gen/2)):
    goukei += 2 * ran[i + 1]
else:
  for i in range(int((gen-1)/2)):
    goukei += 2 * ran[i + 1]
  goukei += ran[i + 2]

print(goukei)

Submission status: Accepted

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

Submission status: Accepted

Solution code:
n = int(input())

A = [int(x) for x in input().split()] #yoko

A.sort(reverse=True)
#print(A)
#A1 = A[1:n-1]
ans = A[0]

count = 1
guuki = 0
i = 1

while count < n-1:
    ans += A[i]

    guuki += 1
    count += 1
    if guuki != 1:
        guuki = 0
        i += 1




print(ans)

Submission status: Accepted

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

def li():
    return [int(x) for x in input().split()]

N = int(input())
A = li()

A.sort(reverse=True)

B = [A[i] for i in range(N) if i < N//2]

# 9 8 7 6 5
# 9 1 8 2 7 3 6 4 5
# 9 6 8 7
# 9+8+8+7+7+6+6+5

# 8 7 6 5
# 8 1 7 2 6 3 5 4
# 8+7+6+5+5+6+7

if N % 2 == 1:
    B = [A[i] for i in range(N) if i < N // 2 + 1]
    sm = B[0] + B[-1] + sum(B[i]*2 for i in range(N//2) if 0 < i)
    print(sm)
else:
    sm = B[0] + sum(B[i]*2 for i in range(N//2) if 0 < i)
    print(sm)

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]
	ans = 0
	maxs = 0
	cnt = 0
	fst = True

	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)

			if tmp == val:
				pgt.put(val)
				cnt += 1
			else:
				pgt.put(val)
				if cnt == N:
					pgt.put(val)

	#print(ansans)
	print(sum(ansans))


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

Submission status: Accepted

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

Submission status: Accepted

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

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

ret = A[0]

cnt = 2
for i in range(1, N):
    for j in range(2):
        if cnt == N:
            print(ret)
            exit()
        ret += A[i]
        cnt += 1

print(ret)

Submission status: Accepted

Solution code:
N = int(input())
A = list(map(int,input().split()))
A.sort()
k = N - 2
a = A.pop()
ans = a
n = k // 2
for i in range(n):
    a = A.pop()
    ans += 2*a
if k - 2*n == 1:
    ans += A[-1]

print(ans)

Submission status: Accepted

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

current = 1
count = 0
comfort = Alist[0]
for i in range(2,N):
  if (count < 2):
    count += 1
    comfort += Alist[current]
  else:
    count = 1
    current += 1
    comfort += Alist[current]
    
    

print(comfort)

Submission status: Accepted

Solution code:
from collections import deque

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

Submission status: Accepted

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

def main():
    N = int(readline())
    A = [int(i) for i in readline().split()]
    A.sort(reverse=True)

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

    if N % 2 == 1:
        ans -= A[N // 2]
    
    print(ans)


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
import sys
import math

def main():
  # Xはもっとも近い整数，Nは与えられるP
  X = int(input())

  if X % 2 ==0:
    # listを取得
    arr = list(map(int, input().split()))
    arr = sorted(arr, reverse=True)

    nu = X/2
    arr2 = arr[0:int(nu)]
    print(sum(arr2)*2-arr2[0])
  else:
    arr = list(map(int, input().split()))
    arr = sorted(arr, reverse=True)

    nu = int(math.floor(X/2))
    arr2 = arr[0:nu]
    print(sum(arr2)*2+arr[nu]-arr2[0])

  
  # 正常終了
  sys.exit()

if __name__ == '__main__':
    main()

Submission status: Accepted

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

# from math import gcd
from fractions import gcd
from collections import Counter, deque, defaultdict
from heapq import heappush, heappop, heappushpop, heapify, heapreplace, merge
from bisect import bisect_left, bisect_right, bisect, insort_left, insort_right, insort
from itertools import accumulate, product, permutations, combinations, combinations_with_replacement

N = int(input())
A = [int(_) for _ in input().split()]
A = sorted(A, reverse=True)

ret = A[0]
ct = 0
ni = []
for i in range(1, N-1):

    ret += A[(i+1) // 2]

print(ret)

Submission status: Accepted

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

Submission status: Accepted

Solution code:
n = int(input())
a = list(map(int,input().split()))
a.sort() #並べかえ
cnt = 0 
ans = a[-1]*-1 
c = 1
while cnt!=n:
    cnt+=1
    if c==1:
        k=a.pop()
    ans += k
    c *= -1

print(ans)

Submission status: Accepted

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

A.sort(reverse = True)


ans2 = A[0]
cnt = 0
j = 1
for i in range(1,N-1):
    if cnt == 2:
        j += 1
        cnt = 0
    ans2 += A[j]
    cnt += 1

print(ans2)

Submission status: Accepted

Solution code:
N=int(input())
A=list(map(int,input().split()))
A.sort()
count=0
j=1
for i in range(1,N):
    count+=A[len(A)-j]
    if i%2==1:
        j+=1
print(count)

Submission status: Accepted

Solution code:
import math
from functools import reduce
from collections import deque
import sys
sys.setrecursionlimit(10**7)

def input():
    return sys.stdin.readline().strip()

# スペース区切りの入力を読み込んで数値リストにして返します。
def get_nums_l():
    return [ int(s) for s in input().split(" ")]

# 改行またはスペース区切りの入力をすべて読み込んでイテレータを返します。
def get_all_int():
    return map(int, open(0).read().split())

def log(*args):
    print("DEBUG:", *args, file=sys.stderr)

def main():
    INF = 999999999999999999999999
    MOD = 10**9+7

    n,*A = get_all_int()
    A = list(A)
    A.sort(reverse=True)

    c = 1
    ans = A[0]
    i = 1
    flag = False
    while(c < n-1):
        ans += A[i]
        c += 1
        if flag:
            i+=1
            flag = False
        else:
            flag = True
    
    print(ans)


main()

Submission status: Accepted

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

Submission status: Accepted

Solution code:
N = int(input())
*A, = 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:

def main():
  n = int(input())

  arr = sorted(map(int, input().split()), reverse=True)

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

  print(ans)


main()