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>
using namespace std;
int A[1000][2], SortedA[1000][2], NumT[1000];
bool comp[1000] = {};
vector<int> Typelist[1000];
int MIN = 100000;
void sorts(int n) {
  priority_queue<pair<int, int> > PQ;
  for (int i = 0; i < n; i++) {
    PQ.push(make_pair(-1 * A[i][1], A[i][0]));
  }
  for (int i = 0; i < n; i++) {
    SortedA[i][0] = PQ.top().second;
    SortedA[i][1] = (-1) * PQ.top().first;
    PQ.pop();
  }
}
void trace(int i, int type) {
  while (!comp[i]) {
    comp[i] = true;
    Typelist[type - 1].push_back(i);
    i = SortedA[i][0];
  }
}
int makeType(int n) {
  int type = 0;
  for (int i = 0; i < n; i++) {
    if (!comp[i]) {
      type++;
      trace(i, type);
    }
  }
  return type;
}
int rec(int type) {
  if (Typelist[type].size() == 1) return 0;
  if (Typelist[type].size() == 2) {
    return A[Typelist[type][0]][1] + A[Typelist[type][1]][1];
  }
  int minc = 100000, sum = 0;
  int n = Typelist[type].size();
  for (int i = 0; i < n; i++) {
    sum += A[Typelist[type][i]][1];
    if (minc > A[Typelist[type][i]][1]) minc = A[Typelist[type][i]][1];
  }
  sum -= minc;
  return sum + min((n - 1) * minc, (n - 1) * MIN + 2 * (MIN + minc));
}
int main() {
  int N, NofT;
  cin >> N;
  for (int i = 0; i < N; i++) {
    scanf("%d", &A[i][1]);
    A[i][0] = i;
    if (MIN > A[i][1]) MIN = A[i][1];
  }
  sorts(N);
  NofT = makeType(N);
  int cost = 0;
  for (int i = 0; i < NofT; i++) {
    cost += rec(i);
  }
  printf("cost = %d\n", cost);
  return 0;
}
