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
def calc_loop_cost(loop, min_w):
    if len(loop) == 1:
        return 0
    elif len(loop) == 2:
        return loop[0] + loop[1]
    else:
        cost1 = sum(loop) + (len(loop) - 2) * min(loop)
        cost2 = sum(loop) + min(loop) + (len(loop) + 1) * min_w
        return min(cost1, cost2)

n = int(input())
org_list = [int(s) for s in input().split()]
sorted_list = sorted(org_list)
check_list = [False] * n
loop_list = []
for i in range(n):
    if check_list[i]:
        continue

    loop = []
    check_list[i] = True
    loop.append(org_list[i])
    next_idx = sorted_list.index(org_list[i])
    while next_idx != i:
        check_list[next_idx] = True
        loop.append(org_list[next_idx])
        next_idx = sorted_list.index(org_list[next_idx])

    loop_list.append(loop)

min_w = sorted_list[0]
cost_sum = 0
for lp in loop_list:
    cost_sum += calc_loop_cost(lp, min_w)

print(cost_sum)
