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
n = int(input())
W = list(map(int, input().split()))

W_org = W[:]
W_org_idx = {w:i for i, w in enumerate(W_org)}
W_srt = list(sorted(W[:]))
W_srt_idx = {w:i for i, w in enumerate(W_srt)}

#print(W_org)
#print(W_org_idx)
#print(W_srt)
#print(W_srt_idx)


def rec(idx, ret):
    if W_org[idx] in ret:
        return ret
    
    ret.append(W_org[idx])
    idx = W_srt_idx[W_org[idx]]
    return rec(idx, ret)

ans = 0
searched = set()
all_min_r = min(W_org)
for i in range(n):    
    if W_org[i] in searched:
        continue
    ret = rec(i, [])
    for r in ret:
        searched.add(r)
    
    if len(ret) == 1:
        continue
    elif len(ret) == 2:
        ans += sum(ret)
    else:
        #print(ret)
        min_r = min(ret)
        ans_a = sum(ret) + len(ret)*min_r - 2*min_r
        
        ans_b = 2*(all_min_r+min_r) + (sum(ret)-min_r+all_min_r) + len(ret)*all_min_r - 2*all_min_r
        ans += min(ans_a, ans_b)

print(ans)
        
    
    

