You are given $n$ integers $w_i (i = 0, 1, ..., n-1)$ to be sorted in ascending order. You can swap two integers $w_i$ and $w_j$. Each swap operation has a cost, which is the sum of the two integers $w_i + w_j$. You can perform the operations any number of times.

Write a program which reports the minimal total cost to sort the given integers.

Constraints

* $1 \leq n \leq 1,000$
* $0 \leq w_i\leq 10^4$
* $w_i$ are all different

Input

In the first line, an integer $n$ is given. In the second line, $n$ integers $w_i (i = 0, 1, 2, ... n-1)$ separated by space characters are given.

Output

Print the minimal cost in a line.

Examples

Input

5
1 5 3 4 2


Output

7


Input

4
4 3 2 1


Output

10
from heapq import *
import sys

sys.setrecursionlimit(10 ** 6)
int1 = lambda x: int(x) - 1
p2D = lambda x: print(*x, sep="\n")

def main():
    def update(j, min_w, sum_w, wn):
        j = ia[j][0]
        fin[j] = True
        w = ia[j][1]
        if w < min_w: min_w = w
        return j, min_w, sum_w + w, wn + 1

    inf = 10 ** 16
    n = int(input())
    aa = list(map(int, input().split()))
    ia = [[i, a] for i, a in enumerate(aa)]
    ia.sort(key=lambda x: x[1])
    #print(ia)
    fin = [False] * n
    min_a = ia[0][1]
    ans = 0
    for i in range(n):
        if fin[i]: continue
        min_w = inf
        sum_w = 0
        wn = 0

        j, min_w, sum_w, wn = update(i, min_w, sum_w, wn)
        if i == j: continue

        while j != i:
            j, min_w, sum_w, wn = update(j, min_w, sum_w, wn)

        ans += min(sum_w + min_w * (wn - 2), sum_w + min_a * (wn + 1) + min_w)
    print(ans)

main()

