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 <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#define _USE_MATH_DEFINES
#include <cmath>

#define rep(i, n)     for (int (i) = 0; (i) < (n); (i)++)
#define rep1(i, n)    for (int i = 1; i <= (int)(n); i++)

using namespace std;
typedef long long ll;

const int MAXN = 1000;
const int MAXV = 10100;

int main() {
   int n, W[MAXN], W_sort[MAXN], cnt[MAXN], num[MAXV];
   int min_w = 10100;
   int ans = 0;

   cin >> n;
   rep(i, n) {
      scanf("%d", &W[i]);
      min_w = min(min_w, W[i]);
      W_sort[i] = W[i];
   }
   rep(i, MAXN) {
      cnt[i] = 0;
   }
   sort(W_sort, W_sort + n);
   rep(i, n) {
      num[W_sort[i]] = i;
   }


   for (int i = 0; i < n; i++) {
      if (cnt[i] == 1) continue;
      int j = i;
      int csum = 0;
      int cmin = 10100;
      int cntl = 0;
      do {
         cntl++;
         csum += W[j];
         cmin  = min(cmin, W[j]);
         cnt[j] = 1;
         j = num[W[j]];
      } while (i != j);
      ans += min(csum + cmin * (cntl - 2), csum + min_w * (cntl + 1) + cmin);
   }

   cout << ans << endl;
   return(0);
}

