import heapq





def main():

    n = int(eval(input()))

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

    As_sort = sorted(As, reverse=True)

    ans = 0

    q = []

    heapq.heappush(q, -As_sort[0])

    for i in range(1, n):

        tmp = heapq.heappop(q)

        tmp *= -1

        ans += tmp

        heapq.heappush(q, -As_sort[i])

        heapq.heappush(q, -As_sort[i])

    print(ans)





if __name__ == "__main__":

    main()

import heapq





def main():

    n = int(eval(input()))

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

    ans = 0

    q = []

    heapq.heappush(q, -As[0])

    for i in range(1, n):

        tmp = -heapq.heappop(q)

        ans += tmp

        heapq.heappush(q, -As[i])

        heapq.heappush(q, -As[i])

    print(ans)





if __name__ == "__main__":

    main()

import heapq


def main():
    n = int(eval(input()))
    As = list(map(int, input().split()))
    As_sort = sorted(As, reverse=True)
    ans = 0
    q = []
    heapq.heappush(q, -As_sort[0])
    for i in range(1, n):
        tmp = heapq.heappop(q)
        tmp *= -1
        ans += tmp
        heapq.heappush(q, -As_sort[i])
        heapq.heappush(q, -As_sort[i])
    print(ans)


if __name__ == "__main__":
    main()

import heapq


def main():
    n = int(eval(input()))
    As = sorted(list(map(int, input().split())))[::-1]
    ans = 0
    q = []
    heapq.heappush(q, -As[0])
    for i in range(1, n):
        tmp = -heapq.heappop(q)
        ans += tmp
        heapq.heappush(q, -As[i])
        heapq.heappush(q, -As[i])
    print(ans)


if __name__ == "__main__":
    main()

-    As = list(map(int, input().split())) -    As_sort = sorted(As, reverse=True) +    As = sorted(list(map(int, input().split())))[::-1] -    heapq.heappush(q, -As_sort[0]) +    heapq.heappush(q, -As[0]) -        tmp = heapq.heappop(q) -        tmp *= -1 +        tmp = -heapq.heappop(q) -        heapq.heappush(q, -As_sort[i]) -        heapq.heappush(q, -As_sort[i]) +        heapq.heappush(q, -As[i]) +        heapq.heappush(q, -As[i])