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 L[2000 / 2 + 2], R[2000 / 2 + 2];
long long merge(int A[], int left, int right, int mid) {
  int i = 0, j = 0;
  int n1 = mid - left, n2 = right - mid;
  long long cnt = 0;
  for (int k = 0; k < n1; k++) L[k] = A[left + k];
  for (int k = 0; k < n2; k++) R[k] = A[mid + k];
  L[n1] = R[n2] = 20000;
  for (int k = left; k < right; k++) {
    if (L[i] <= R[j]) {
      A[k] = L[i++];
    } else {
      cnt += A[k] + R[j];
      A[k] = R[j];
      j++;
    }
  }
  return cnt;
}
long long inversion(int A[], int left, int right) {
  long long cnt1, cnt2, m;
  int mid;
  if (left + 1 < right) {
    mid = (left + right) / 2;
    cnt1 = inversion(A, left, mid);
    cnt2 = inversion(A, mid, right);
    m = merge(A, left, right, mid);
    return cnt1 + cnt2 + m;
  } else {
    return 0;
  }
}
int main() {
  int n, A[2000], B[2000], C[2000];
  cin >> n;
  for (int i = 0; i < n; i++) {
    cin >> A[i];
    B[i] = C[i] = A[i];
  }
  inversion(A, 0, n);
  int j = 0;
  for (int i = 0; i < n; i++) {
    if (B[i] != A[i]) C[j++] = B[i];
  }
  long long ans = inversion(C, 0, j);
  cout << ans << endl;
  return 0;
}
