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:
# coding: utf-8
#import numpy as np
import re
import math
from collections import defaultdict,deque,Counter
from fractions import Fraction
import bisect
import itertools
from itertools import accumulate
from copy import deepcopy
import heapq
import random
import time
import os
import sys
from functools import lru_cache,reduce
readline=sys.stdin.readline
sys.setrecursionlimit(100000)
alp="abcdefghijklmnopqrstuvwxyz"
numbers="0123456789"
mod=int(10**9+7)
inf=int(10**19)
class Set():
    def __init__(self,A=[]):
        self.heap=[]
        self.dic=defaultdict(bool)
        self.size=0
        for a in A:self.add(a)
    
    def __str__(self):
        return str(self.heap)
    
    def add(self,x):
        if not self.find(x):
            heapq.heappush(self.heap,x)
            self.dic[x]=True
            self.size+=1

    def remove(self,x):
        if self.find(x):
            self.dic[x]=False
            self.size-=1

    def find(self,x):
        return self.dic[x]
    
    def top(self):
        while self.heap and self.dic[self.heap[0]]==False:
            heapq.heappop(self.heap)
        if self.heap:return self.heap[0]
        else:return None

    def pop(self):
        ret=None
        if self.heap:
            ret=self.top()
            self.remove(ret)
        return ret
class multiset():
    def __init__(self,A=[]):
        self.heap=[]
        self.dic=defaultdict(int)
        self.size=0
        for a in A:self.add(a)
    
    def __str__(self):
        return str(self.heap)
    
    def add(self,x):
        heapq.heappush(self.heap,x)
        self.dic[x]+=1
        self.size+=1

    def remove(self,x):
        if self.dic[x]>0:
            self.dic[x]-=1
            self.size-=1
    
    def count(self,x):
        return self.dic[x]

    def find(self,x):
        return self.dic[x]>0
    
    def top(self):
        while self.heap and self.dic[self.heap[0]]==0:
            heapq.heappop(self.heap)
        if self.heap:return self.heap[0]
        else:return None

    def pop(self):
        ret=None
        if self.heap:
            ret=self.top()
            self.remove(ret)
        return ret
class Edge():
    def __init__(self,x,y,val=1):
        self.x=x
        self.y=y
        self.val=val
class unionfind():
    def __init__(self,n):
        self.n=n
        self.P=[a for a in range(n)]
        self.rank=[0]*n
 
    def find(self,x):
        if(x!=self.P[x]):
            self.P[x]=self.find(self.P[x])
        return self.P[x]
 
    def same(self,x,y):
        return self.find(x)==self.find(y)
 
    def link(self,x,y):
        if self.rank[x]<self.rank[y]:
            self.P[x]=y
        elif self.rank[y]<self.rank[x]:
            self.P[y]=x
        else:
            self.P[x]=y
            self.rank[y]+=1
 
    def unite(self,x,y):
        self.link(self.find(x),self.find(y))
 
    def size(self):
        S=set()
        for a in range(self.n):
            S.add(self.find(a))
        return len(S)
def yn(b):print("yes" if b else "no")
def Yn(b):print("Yes" if b else "No")
def YN(b):print("YES" if b else "NO")
def ispow(a,b):
    now=b
    while now<a:
        now*=b
    return now==a
def getbin(num,size):
    A=[0]*size
    for a in range(size):
        if (num>>(size-a-1))&1==1:
            A[a]=1
        else:
            A[a]=0
    return A
def getfacs(n,mod_=0):
    A=[1]*(n+1)
    for a in range(2,len(A)):
        A[a]=A[a-1]*a
        if(mod_>0):A[a]%=mod_
    return A
def comb(n,r,mod,fac):
    if(n-r<0):return 0
    return (fac[n]*pow(fac[n-r],mod-2,mod)*pow(fac[r],mod-2,mod))%mod
def nextcomb(num,size):
    x=num&(-num)
    y=num+x
    z=num&(~y)
    z//=x
    z=z>>1
    num=(y|z)
    if(num>=(1<<size)):return False
    else:return num
def getprimes(n):
    if n==0:return []
    A=[True]*(n+1)
    A[0]=False
    A[1]=False
    for a in range(2,n+1):
        if A[a]:
            for b in range(a*2,n+1,a):
                A[b]=False
    ret=[]
    for a in range(n+1):
        if(A[a]):ret.append(a)
    return ret
def isprime(num):
    if(num<=1):return False
    i=2
    while i*i<=num:
       if(num%i==0):return False
       i+=1
    return True
def ifelse(b,t,f):return t if b else f
def factorize(n):
    b = 2
    ret=defaultdict(int)
    while b * b <= n:
        while n % b == 0:
            n //= b
            ret[b]+=1
        b+=1
    if n > 1:ret[n]+=1
    return ret
def inputintlist(row=1): 
    if row==1:
        ret=list(map(int,input().split()))
    else:
        ret=[None]*row
        for a in range(row):
            ret[a]=int(input())
    return ret
def inputfloatlist(row=1): 
    if row==1:
        ret=list(map(float,input().split()))
    else:
        ret=[None]*row
        for a in range(row):
            ret[a]=float(input())
    return ret
def istanchouzouka(A):
    f=True
    prev=min(A)-1
    for a in A:
        if prev>=a:
            f=False
        prev=a
    return f
def istanchouhigensyou(A):
    f=True
    prev=min(A)-1
    for a in A:
        if prev>a:
            f=False
        prev=a
    return f
def getallsum(A):
    s=sum(A)
    dp=defaultdict(int)
    dp[0]=1
    for a in range(0,len(A)):
        for b in range(s,-1,-1):
            if b-A[a]>=0:
                dp[b]+=dp[b-A[a]]
    return dp
def yuukoutomukou(edges):
    ret=deepcopy(edges)
    for edge in edges:
        if not edge.x==edge.y:
            ret.append(Edge(edge.y,edge.x,edge.val))
    return ret
def dijkstra(edges,V,start):
    mincost=[inf]*V
    G=[[] for a in range(V)]
    for edge in edges:
        G[edge.x].append([edge.val,edge.y])
    Q=PriorityQueue()
    Q.put([0,start])#[cost,x]
    while not Q.empty():
        nowcost,nowx=Q.get()
        if mincost[nowx]==inf:
            mincost[nowx]=nowcost
            for cost,y in G[nowx]:
                newcost=nowcost+cost
                Q.put([newcost,y])
    return mincost
def warshallfloyd(edges,V):
    mincost=[[inf for b in range(V)] for a in range(V)]
    for a in range(V):mincost[a][a]=0
    for edge in edges:
        mincost[edge.x][edge.y]=min(mincost[edge.x][edge.y],edge.val)#x→yが複数ある場合のためにmin()する
    for k in range(V):
        for s in range(V):
            for t in range(V):
                if mincost[s][k]==inf or mincost[k][t]==inf:continue
                mincost[s][t]=min(mincost[s][t],mincost[s][k]+mincost[k][t])
    return mincost
def bellemanford(edges,V,start):
    mincost=[inf]*V
    mincost[start]=0
    for _ in range(V):
        for edge in edges:
            if mincost[edge.x]==inf:continue
            mincost[edge.y]=min(mincost[edge.y],mincost[edge.x]+edge.val)
    return mincost
def getmd(x1,y1,x2,y2):return abs(x1-x2)+abs(y1-y2)
def geted(x1,y1,x2,y2):return math.sqrt((x1-x2)**2+(y1-y2)**2)
class fordfulkerson():
    def __init__(self,edges,V,s,t):
        self.V=V
        self.used=[False]*V
        self.G=[[] for a in range(V)]
        self.s=s
        self.t=t
        for edge in edges:
            self.G[edge.x].append({"x":edge.x,"y":edge.y,"cap":edge.val,"rev":len(self.G[edge.y])})
            self.G[edge.y].append({"x":edge.y,"y":edge.x,"cap":0,"rev":len(self.G[edge.x])-1})
    def dfs(self,v,t,f=inf):
        if v==t:return f
        self.used[v]=True
        for a in range(len(self.G[v])):
            x=self.G[v][a]["x"]
            y=self.G[v][a]["y"]
            cap=self.G[v][a]["cap"]
            rev=self.G[y][self.G[x][a]["rev"]]
            if self.used[y] or cap==0:continue
            f2=self.dfs(y,t,min(f,cap))
            if f2>0:
                self.G[v][a]["cap"]-=f2
                rev["cap"]+=f2
                return f2
        return 0
    def maxflow(self):
        flow=0
        while True:
            self.used=[False]*V
            zouka=self.dfs(self.s,self.t)
            if zouka==0:break
            flow+=zouka
        return flow
def zipsort(*args):
    ziplist=sorted(zip(*args))
    for a in range(len(args)):
        for b in range(len(ziplist)):
            args[a][b]=ziplist[b][a]
def zipreverse(*args):
    ziplist=list(zip(*args))
    rev=[]
    for a in range(len(ziplist)-1,-1,-1):
        rev.append(ziplist[a])
    for a in range(len(args)):
        for b in range(len(rev)):
            args[a][b]=rev[b][a]

######################################################################################################
n=int(input())
A=inputintlist()
A.sort()
A.reverse()
S=[]
S.append([A[1],A[0]])
S.append([A[1],A[0]])
si=0
ans=A[0]
for a in range(2,n):
    m,M=S[si]
    S.append([A[a],M])
    S.append([A[a],m])
    ans+=m
    si+=1
print(ans)

Submission status: Accepted

Solution code:
import sys
#sys.exit()
#sorted( ,reverse=True)
N = int(input())
#S,T = map(int, input().split())
A = list(map(int, input().split()))
#A = [int(input()) for _ in range(N)]
B = sorted(A,reverse=True)
ans = B[0]
cnt = 1
#print(B,ans)
for i in range(1,N-1):
    ans += B[cnt]
    #print(ans,B[cnt],cnt)

    if i%2 == 0:
        cnt += 1
    #print(ans,B[cnt],cnt)

print(ans)

#cnt = 0
#cnt += 1



#print(N)
#print(S,T)
#print(A)
#print('Yes')
#print('No')
#print(cnt)

Submission status: Accepted

Solution code:
N = int(input())
A = [int(i) for i in input().split()]
A.sort(reverse=True)
ans = A[0]
cur = A[1]
num = 1
for i in range(N-2):
    if i%2 == 0:
        ans += A[num]
    else:
        ans += A[num]
        num += 1
print(ans)

Submission status: Accepted

Solution code:
n=int(input())
l=sorted(list(map(int,input().split())),reverse=1)
from heapq import heapify, heappop, heappush
h=[-l[0]]

ans=0
for i in range(1,n):
    p=-heappop(h)
    ans+=p
    heappush(h,-l[i])
    heappush(h,-l[i])
print(ans)

Submission status: Accepted

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

a.sort(reverse=True)
ans=a[0]+(sum(a[1:(n//2)])*2)
if n%2!=0:
    ans+=a[n//2]

print(ans)

Submission status: Accepted

Solution code:
from collections import deque

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

A.sort(reverse=True)
X=deque([A[0]])

K=0
for b in A[1:]:
    a=X.popleft()
    K+=a
    X.append(b)
    X.append(b)

print(K)

Submission status: Accepted

Solution code:
n = int(input())
a = list(map(int,input().split()))
a.sort(reverse=True)
res = a[0]
a.pop(0)

num = (n - 2) // 2
num1 = (n - 2) % 2
res += sum(a[:num]) * 2 + a[num] * num1
print(res)

Submission status: Accepted

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

now = a[0]
i = 0
while i+2 < n:
    now += a[i//2 + 1]
    i+=1
print(now)

Submission status: Accepted

Solution code:
import sys

read = sys.stdin.read
readline = sys.stdin.readline
readlines = sys.stdin.readlines
sys.setrecursionlimit(10 ** 9)
INF = 1 << 60
MOD = 1000000007


def main():
    N, *A = map(int, read().split())

    A.sort(reverse=True)
    
    m = (N+1) // 2
    
    ans = sum(A[:m]) + sum(A[1:N-m])
    print(ans)
    return


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import math
n=int(input())
a=input()
al=[int(i) for i in a.split()]
al.sort(reverse=True)
ans=al[0]
for i in range(math.floor((n-2)/2)):
    ans+=al[i+1]*2
if round((n-2)/2)-(n-2)/2!=0:
    ans+=al[math.floor((n-2)/2)+1]
print(ans)

Submission status: Accepted

Solution code:
from heapq import *

N,*A = map(int, open(0).read().split())
ai = [x * (-1) for x in A]
heapify(ai)
ans = heappop(ai) * (-1)
searching = 1
for i in range(N-2):
    if i % 2 == 0:
        temp = heappop(ai) * (-1)
    ans += temp
print(ans)

Submission status: Accepted

Solution code:
from queue import deque

class LinkedListNode:
	def __init__(self, value):
		self.value = value
		self.left = self
		self.right = self

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

A_list.sort()

circle = LinkedListNode(A_list.pop())
not_used = deque((circle, ))

total = 0
while len(A_list) > 0:
	value = A_list.pop()
	
	new_node = LinkedListNode(value)
	while True:
		head = not_used[0]
		if head.left.value >= head.value:
#			print("l", head.left.value, value, head.value)
			total += head.value
			new_node.right = head
			new_node.left = head.left
			head.left.right = new_node
			head.left = new_node
			break
		elif head.right.value >= head.value:
#			print("r", head.right.value, value, head.value)
			total += head.value
			new_node.right = head.right
			new_node.left = head
			head.right.left = new_node
			head.right = new_node
			break
		not_used.popleft()
	not_used.append(new_node)

print(total)

Submission status: Accepted

Solution code:
#                          JAI SHREE RAM

import math; from collections import *
import sys; from functools import reduce

# sys.setrecursionlimit(10**6)
def get_ints(): return map(int, input().strip().split())
def get_list(): return list(get_ints())
def get_string(): return list(input().strip().split())
def printxsp(*args): return print(*args, end="")
def printsp(*args): return print(*args, end=" ")

UGLYMOD = int(1e9)+7; SEXYMOD = 998244353; MAXN = int(1e5)

# sys.stdin=open("input.txt","r");sys.stdout=open("output.txt","w")

# for _testcases_ in range(int(input())):
n = int(input())
li = sorted(get_list(), reverse = True)

ans = li[0]
pos = 1
enter = 2
while enter < n:
    ans += li[pos]*2
    enter += 2
    pos += 1
    # print(ans)
if enter == n + 1:
    ans -= li[pos-1]
print(ans)


'''
>>> COMMENT THE STDIN!! CHANGE ONLINE JUDGE !!
THE LOGIC AND APPROACH IS MINE @luctivud ( UDIT GUPTA )
Link may be copy-pasted here if it's taken from other source.
DO NOT PLAGIARISE.
>>> COMMENT THE STDIN!! CHANGE ONLINE JUDGE !!
'''

Submission status: Accepted

Solution code:
N = int(input())
A = list(map(int, input().split()))
A.sort()
A = A[::-1]
ans = A[0]
for i in range(N-2):
  ans += A[1 + i//2]
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
Q = deque()
Q.append(A[0])
for a in A[1:]:
    b = Q[0]
    if a == b:
        Q.append(a)
        ans += b
    else:
        b = Q.popleft()
        ans += b
        Q.append(a)
        Q.append(a)
print(ans)

Submission status: Accepted

Solution code:
#: Author - Soumya Saurav
import sys,io,os,time
from collections import defaultdict
from collections import OrderedDict
from collections import deque
from itertools import combinations
from itertools import permutations
import bisect,math,heapq
alphabet = "abcdefghijklmnopqrstuvwxyz"

input = sys.stdin.readline

########################################
n = int(input())
arr = list(map(int , input().split()))
arr.sort(reverse = True)
ptr = 1
s = arr[0]
n-=2
while n:
	s+=arr[ptr]
	n-=1
	if n == 0: break
	s+=arr[ptr]
	n-=1
	ptr+=1
print(s)

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 = list(reversed(sorted(a)))

result = a[0]
n -= 2

i = 1

while n > 0:
	result += a[i]
	n -= 1
	if n > 0:
		result += a[i]
		n -= 1

	i += 1

print(result)

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

Solution code:
from heapq import heapify, heappop, heappush
N,*A=map(int, open(0).read().split())
A=sorted(A, reverse=True)
L=[0]*N
R=[0]*N
ans=0
L[0]=0
R[0]=0
H=[(-A[0],0,0)]
heapify(H)
for i in range(1,N):
    a=A[i]
    p,pl,pr=heappop(H)
    ans+=-p
    L[pr]=i
    R[pl]=i
    L[i]=pl
    R[i]=pr
    heappush(H,(-min(A[pl],a),pl,i))
    heappush(H,(-min(A[pr],a),i,pr))
print(ans)

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(1000000000)
import math
from math import gcd
def lcm(a, b): return a * b // gcd(a, b)
from itertools import count, permutations, chain, product
from functools import lru_cache
from collections import deque, defaultdict
from pprint import pprint
ii = lambda: int(input())
mis = lambda: map(int, input().split())
lmis = lambda: list(mis())
INF = float('inf')
N1097 = 10**9 + 7

def meg(f, ok, ng):
    while abs(ok-ng)>1:
        mid = (ok+ng)//2
        if f(mid):
            ok=mid
        else:
            ng=mid
    return ok

def get_inv(n, modp):
    return pow(n, modp-2, modp)

def factorials_list(n, modp):    # 10**6
    fs = [1]
    for i in range(1, n+1):
        fs.append(fs[-1] * i % modp)
    return fs

def invs_list(n, fs, modp):     # 10**6
    invs = [get_inv(fs[-1], modp)]
    for i in range(n, 1-1, -1):
        invs.append(invs[-1] * i % modp)
    invs.reverse()
    return invs

def comb(n, k, modp):
    num = 1
    for i in range(n, n-k, -1):
        num = num * i % modp
    den = 1
    for i in range(2, k+1):
        den = den * i % modp
    return num * get_inv(den, modp) % modp

def comb_from_list(n, k, modp, fs, invs):   
    return fs[n] * invs[n-k] * invs[k] % modp

#

class UnionFindEx:
    def __init__(self, size):
        #正なら根の番号、負ならグループサイズ
        self.roots = [-1] * size
    def getRootID(self, i):
        r = self.roots[i]
        if r < 0:   #負なら根
            return i
        else:
            r = self.getRootID(r)
            self.roots[i] = r
            return r
    def getGroupSize(self, i):
        return -self.roots[self.getRootID(i)]
    def connect(self, i, j):
        r1, r2 = self.getRootID(i), self.getRootID(j)
        if r1 == r2:
            return False
        if self.getGroupSize(r1) < self.getGroupSize(r2):
            r1, r2 = r2, r1
        self.roots[r1] += self.roots[r2]    #サイズ更新
        self.roots[r2] = r1
        return True

Yes = 'Yes'
No = 'No'


def main():
    N=ii()
    A=lmis()
    A.sort()
    q = deque()
    q.append(A.pop())
    ans = 0
    while A:
        s = q.popleft()
        ans += s
        ns = A.pop()
        q.append(ns)
        q.append(ns)
    print(ans)









main()

Submission status: Accepted

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

print(S)

Submission status: Accepted

Solution code:
import sys
n=int(input())
a=list(map(int,input().split()))
def nibai(n):
  return n*2
a.sort(reverse=True)
sc=a[0]
if n==2:
  print(sc)
  sys.exit() 
a=a[1:]
b=list(map(nibai,a))
sc+=sum(b[:(n//2)-1])
if n%2==0:
  print(sc)
else:
  print(sc+a[(n//2)-1])

Submission status: Accepted

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

Submission status: Accepted

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

a.sort()
a.reverse()

ret = 0
ret += a[0]

for i in range(1, len(a)):
    tmp = a[i]
    if i * 2 < len(a):
        ret += tmp
    if i * 2 + 1 < len(a):
        ret += tmp

print(ret)

Submission status: Accepted

Solution code:
N = int(input())
A = sorted([int(_) for _ in input().split()], reverse=1)
#0+ a + b + b + c + c + d + d + e + e + f + f
#1   2   3   4   5   6   7  8   9  10  11 12
if N % 2:
    print(2 * sum(A[:N // 2]) - A[0] + A[N // 2])
else:
    print(2 * sum(A[:N // 2]) - A[0])

Submission status: Accepted

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

Submission status: Accepted

Solution code:

N = int(input())

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

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

print(ans)

Submission status: Accepted

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

Submission status: Accepted

Solution code:
from heapq import heappop, heappush, heapify

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

q = [-a[0]]
ans = 0

for i in range(1, n):
    x = -heappop(q)
    ans += x
    heappush(q, -a[i])
    heappush(q, -a[i])

print(ans)

Submission status: Accepted

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

Submission status: Accepted

Solution code:
# template by 3xC and starkizard.
# contributors: 

#####################################################################################
from __future__ import division, print_function 

import sys
import os
from collections import Counter, deque, defaultdict
import itertools
import math
import io


"""Uncomment modules according to your need"""


# from bisect import bisect_left, bisect_right, insort
# from heapq import heappop, heapify, heappush
# from random import randint as rn
# from Queue import Queue as Q
# from copy import deepcopy
# from decimal import *
# import re
# import operator

#####################################################################################
# this enables you to write python3 code with PyPy2 (Python 2)
if sys.version_info[0] < 3:
    input = raw_input
    range = xrange

    filter = itertools.ifilter
    map = itertools.imap
    zip = itertools.izip

#####################################################################################

"""value of mod"""
MOD = 998244353
mod = 10**9 + 7

"""Uncomment next 4 lines if doing huge recursion"""
# import threading
# threading.stack_size(1<<27)
# sys.setrecursionlimit(10000)

def prepare_factorial(mod=mod):
    """ returns two lists, factorial and inverse factorial modulo argument by default 10**9 +7 """
    # Comment code out when you don't need inverse factorial or vice versa
    fact = [1]
    for i in range(1, 200005):
        fact.append((fact[-1] * i) % mod)

    ifact = [0] * 200005
    ifact[200004] = pow(fact[200004], mod - 2, mod)
    for i in range(200004, 0, -1):
        ifact[i - 1] = (i * ifact[i]) % mod

    return fact, ifact

def modinv(n, p):
    """ returns N inverse modulo p """
    return pow(n, p - 2, p)

def ncr(n, r,  fact, ifact,MOD=mod):
    """ takes 4 arguments: n , r and factorial and inverse factorial lists"""
    t = (fact[n] * (ifact[r]*ifact[n-r]) % MOD)% MOD
    return t


def get_n(Sum):    
    """this function returns the maximum n for which Summation(n) <= Sum"""
    ans = (-1 + sqrt(1 + 8*Sum))//2
    return ans

def sieve(n):
    """ returns a list of prime numbers till n """
    if n < 2: return list()
    prime = [True for _ in range(n + 1)]
    p = 3
    while p * p <= n:
        if prime[p]:
            for i in range(p * 2, n + 1, p):
                prime[i] = False
        p += 2
    r = [2]
    for p in range(3, n + 1, 2):
        if prime[p]:
            r.append(p)
    return r



def divs(n, start=1):
    """ returns a list of all divisors till n """
    divisors = []
    #rdivisors=[]
    for i in range(start, int(math.sqrt(n) + 1)):
        if n % i == 0:
            if n / i == i:
                divisors.append(i)
            else:
                divisors.extend([i, n // i])
    return divisors



def divn(n, primes):
    """ returns the number of divisors, two arguments n and the sieve till n """
    divs_number = 1
    for i in primes:
        if n == 1:
            return divs_number
        t = 1
        while n % i == 0:
            t += 1
            n //= i
        divs_number *= t
    return divs_number


def lrfind(d, x, default=-1):
    """ Takes 2 arguments an iterable and an element. returns a tuple (firstoccurence,lastoccurence) -1 if not found """
    left = right = -1
    for i in range(len(d)):
        if d[i] == x:
            if left == -1: left = i
            right = i
    if left == -1:
        return default, default
    else:
        return left, right

def gcd(x, y): # math.gcd is slower
    """ returns greatest common divisor of x and y """
    while y:
        x, y = y, x % y
    return x

def check_sorted(a):
    ''' returns True/False '''
    for i in range(len(a)-1):
        if a[i]>a[i+1]:
            return False
    return True

def print_arr2d(a):
    for i in a:
        prr(i)
    
def ceil(n, k=1): return n // k + (n % k != 0) #returns math.ceil but protecting against floating inconsistencies
def input(): return sys.stdin.readline().strip()
def ii(): return int(input()) #inputs integer
def mi(): return map(int, input().split()) # inputting space seperated variables for example x,y,z
def li(): return list(map(int, input().split())) #inputting a space seperated list of integers
def lw(): return input().split() #inputting a space seperated list of strings
def lcm(a, b): return abs(a * b) // gcd(a, b) #returns LCM of two arguments
def prr(a, sep=' ', end='\n'): print(sep.join(map(str, a)), end=end) #For printing an iterable with seperator sep as optional second argument (default : " "), ending character (default: "\n") as optional third
def dd(): return defaultdict(int) #returns a dictionary with values defaulted to 0
def ddl(): return defaultdict(list) #returns a dictionary with values defaulted to []
def write(s): return sys.stdout.write(s)












###################################################################
# code goes here
def main(): 
    n=ii()
    a=li()
    a.sort(reverse=True)
    answer=0
    pointer=0
    pcount=0
    for i in range(1,n):
        answer+=a[pointer]
        if pointer==0:
            pointer+=1
        else:
            if pcount==1:
                pcount=0
                pointer+=1
            else:
                pcount+=1
    print(answer)


                

                    




        
    
        
        
    


            


            
                
            

            



                






        
        


    
    
                

    

""" -------- Python 2 and 3 footer by Pajenegod and c1729 ---------"""

py2 = round(0.5)
if py2:
    from future_builtins import ascii, filter, hex, map, oct, zip
    range = xrange

import os, sys
from io import IOBase, BytesIO

BUFSIZE = 8192

class FastIO(BytesIO):
    newlines = 0

    def __init__(self, file):
        self._file = file
        self._fd = file.fileno()
        self.writable = "x" in file.mode or "w" in file.mode
        self.write = super(FastIO, self).write if self.writable else None

    def _fill(self):
        s = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
        self.seek((self.tell(), self.seek(0, 2), super(FastIO, self).write(s))[0])
        return s

    def read(self):
        while self._fill(): pass
        return super(FastIO, self).read()

    def readline(self):
        while self.newlines == 0:
            s = self._fill();
            self.newlines = s.count(b"\n") + (not s)
        self.newlines -= 1
        return super(FastIO, self).readline()

    def flush(self):
        if self.writable:
            os.write(self._fd, self.getvalue())
            self.truncate(0), self.seek(0)


class IOWrapper(IOBase):

    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        if py2:
            self.write = self.buffer.write
            self.read = self.buffer.read
            self.readline = self.buffer.readline
        else:
            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')
# sys.stdin = open('input.txt', 'r')
# sys.stdout = open('output.txt', 'w')

""" main function"""

if __name__ == '__main__':
    main()
    #threading.Thread(target=main).start()

Submission status: Accepted

Solution code:
n = int(input())

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

a.sort(reverse=True)

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

print(kotae)

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:
n, *a = map(int, open(0).read().split())
a.sort(reverse=True)
ans = a[0]
if n%2 == 0:
    for i in range(1, n//2):
        ans += a[i] * 2
else:
    for i in range(1, int(n/2)):
        ans += a[i] * 2
    ans += a[i+1]

print(ans)

Submission status: Accepted

Solution code:
import sys
def Ii():return int(sys.stdin.readline())
def Mi():return map(int,sys.stdin.readline().split())
def Li():return list(map(int,sys.stdin.readline().split()))

n = Ii()
a = sorted(Li(),reverse=True)
ans = a.pop(0)
for i in range(n//2-1):
  ans += 2*a[i]
  
if n%2 == 1:
  ans += a[i+1]  
  
print(ans)

Submission status: Accepted

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

    print(ans)
    


if __name__ == "__main__":
    main()

Submission status: Accepted

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

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

print(ans)