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
#include<bits/stdc++.h>
#define rep(i, n) for (int i = 0; i < (n); ++i) 
#define PI acos(-1)

using namespace std;
using ll = long long;
using P = pair<int, int>;

ll minCostSort(int n, vector<int> as) {
    vector<int> bs(n);
    copy(as.begin(), as.end(), bs.begin());
    sort(bs.begin(), bs.end());
    vector<bool> visited(n);

    int gm = bs[0];
    ll cost = 0;
    rep(i, n) {
        if (visited[i]) continue;

        int cur = i;
        ll s = 0;
        int m = INT_MAX;
        int hop = 0;
        while (!visited[cur]) {
            if (as[cur] < m) m = as[cur];
            s += as[cur];
            visited[cur] = true;
            hop++;
            cur = distance(bs.begin(), lower_bound(bs.begin(), bs.end(), as[cur]));
        }
        cost += min(s + m * (hop - 2), s + m + gm * (hop + 1));
    }
    return cost;
}

int main() {
    cin.tie(0);
    ios::sync_with_stdio(false);

    int n;
    cin>>n;
    vector<int> as(n);
    rep(i, n) cin>>as[i];

    ll ans = minCostSort(n, as);
    cout<<ans<<endl;
}
