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_cost(hoge):
    cost = 0
    hoge_refer = sorted(hoge[:])
    #checker true means that this index have already looked.
    checker = [False] * len(hoge)
    #abs_min is minimum num in input array.
    abs_min = hoge_refer[0]
    #indexer -> key: sorted val, val: zero 2 n-1
    indexer = {hoge_refer[i]:i for i in range(len(hoge_refer))}
    
    for now_index in range(len(hoge)):
        if checker[now_index]:
            continue
        current = now_index
        size = 0
        sum_num = 0
        circle_min = 10 ** 4
        while True:
            checker[current] = True
            size += 1
            val = hoge[current]
            circle_min = min(circle_min, val)
            sum_num += val
            current = indexer[val]
            if checker[current]:
                break
        cost += min(sum_num+(size-2)*circle_min, circle_min+sum_num+(size+1)*abs_min)
    return cost
        
    
if __name__ == '__main__':
    _ = int(input())
    hoge = [int(x) for x in input().split()]
    print(calc_cost(hoge))
