MAX = 1000

VMAX = 10000

n = int(eval(input()))

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

V = [False] * MAX

def solve():

    B = A[:]

    T = [0] * (VMAX + 1)

    B.sort()

    ans = 0

    s = min(VMAX, min(A))

    for i in range(n):

        T[B[i]] = i

    for i in range(n):

        if V[i] : continue

        cur = i

        S = 0

        m = VMAX

        an = 0

        while True:

            V[cur] = True

            an += 1

            v = A[cur]

            m = min(m, v)

            S += v

            cur = T[v]

            if V[cur] : break

        ans += min(S + (an - 2) * m, m + S + (an + 1) * s)

    print(ans)

solve()
VMAX = 10000

n = int(eval(input()))

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

s = min(A)

def solve():

    ans = 0

    V = [False] * n

    B = sorted(A)

    T = [0] * (VMAX + 1)

    for i in range(n):

        T[B[i]] = i

    for i in range(n):

        if V[i]:

            continue

        cur = i

        S = 0

        m = VMAX

        an = 0

        while True:

            V[cur] = True

            an += 1

            v = A[cur]

            m = min(m, v)

            S += v

            cur = T[v]

            if V[cur]:

                break

        ans += min(S + (an - 2) * m, m + S + (an + 1) * s)

    return ans

print((solve()))

MAX = 1000
VMAX = 10000
n = int(eval(input()))
A = [int(i) for i in input().split()]
V = [False] * MAX


def solve():
    B = A[:]
    T = [0] * (VMAX + 1)
    B.sort()
    ans = 0
    s = min(VMAX, min(A))
    for i in range(n):
        T[B[i]] = i
    for i in range(n):
        if V[i]:
            continue
        cur = i
        S = 0
        m = VMAX
        an = 0
        while True:
            V[cur] = True
            an += 1
            v = A[cur]
            m = min(m, v)
            S += v
            cur = T[v]
            if V[cur]:
                break
        ans += min(S + (an - 2) * m, m + S + (an + 1) * s)
    print(ans)


solve()

VMAX = 10000
n = int(eval(input()))
A = list(map(int, input().split()))
s = min(A)


def solve():
    ans = 0
    V = [False] * n
    B = sorted(A)
    T = [0] * (VMAX + 1)
    for i in range(n):
        T[B[i]] = i
    for i in range(n):
        if V[i]:
            continue
        cur = i
        S = 0
        m = VMAX
        an = 0
        while True:
            V[cur] = True
            an += 1
            v = A[cur]
            m = min(m, v)
            S += v
            cur = T[v]
            if V[cur]:
                break
        ans += min(S + (an - 2) * m, m + S + (an + 1) * s)
    return ans


print((solve()))

-MAX = 1000 -A = [int(i) for i in input().split()] -V = [False] * MAX +A = list(map(int, input().split())) +s = min(A) -    B = A[:] +    ans = 0 +    V = [False] * n +    B = sorted(A) -    B.sort() -    ans = 0 -    s = min(VMAX, min(A)) -    print(ans) +    return ans -solve() +print((solve()))