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 main():
    n = int(input())
    array = [int(x) for x in input().split()]
    sorted_array = sorted(array)

    groups = []
    for i in range(len(array)):
        moving_src_val = array[i]
        if not moving_src_val:
            continue
        group = [moving_src_val]
        while True:
            moving_tgt_idx = sorted_array.index(moving_src_val)
            moving_tgt_val = array[moving_tgt_idx]
            if moving_tgt_val in group:
                break
            group.append(moving_tgt_val)
            array[moving_tgt_idx] = False
            moving_src_val = moving_tgt_val
        array[i] = False
        groups.append(group)

    #print(groups)

    min_cost = 0
    min_in_array = sorted_array[0]
    for group in groups:
        n_group = len(group)
        if n_group == 1:
            continue
        min_in_group = min(group)
        sum_without_min = sum(group) - min_in_group

        cost1 = (n_group - 1) * min_in_group
        cost2 = (n_group + 1) * min_in_array + 2 * min_in_group

        if cost1 < cost2:
            min_cost += cost1 + sum_without_min
        else:
            min_cost += cost2 + sum_without_min

    print(min_cost)
    return


main()
