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>
int array[1001];
int sorted[1001];
void swap(int* a, int* b) {
  int tmp = *a;
  *a = *b;
  *b = tmp;
}
int calc_cost(int n, int min_pos, int flag) {
  int loop_pos = min_pos;
  int i, sum = 0;
  int min = array[min_pos];
  do {
    for (i = 0; i < n; i++) {
      if (array[i] == sorted[loop_pos]) {
        sum += array[i] + min;
        if (flag) {
          swap(&array[i], &array[loop_pos]);
        }
        loop_pos = i;
        break;
      }
    }
  } while (min != sorted[loop_pos]);
  return sum;
}
int greedy(int n) {
  int i, j;
  int absolute_min = sorted[0], absolute_min_pos = -1;
  int min = 1000001, min_pos = -1;
  int loop_pos = -1;
  int direct_sum = 0;
  int indirect_sum = 0;
  for (i = 0; i < n; i++) {
    if (array[i] == absolute_min) {
      absolute_min_pos = i;
      break;
    }
  }
  for (i = 0; i < n; i++) {
    if (min > array[i] && sorted[i] != array[i]) {
      min = array[i];
      min_pos = i;
    }
  }
  if (min_pos == -1) {
    return 0;
  }
  direct_sum += calc_cost(n, min_pos, 0);
  swap(&array[min_pos], &array[absolute_min_pos]);
  indirect_sum += array[min_pos] + array[absolute_min_pos];
  indirect_sum += calc_cost(n, min_pos, 0);
  indirect_sum += array[min_pos] + array[absolute_min_pos];
  swap(&array[min_pos], &array[absolute_min_pos]);
  if (direct_sum <= indirect_sum) {
    calc_cost(n, min_pos, 1);
    return direct_sum + greedy(n);
  } else {
    swap(&array[min_pos], &array[absolute_min_pos]);
    calc_cost(n, min_pos, 1);
    swap(&array[min_pos], &array[absolute_min_pos]);
    return indirect_sum + greedy(n);
  }
  return 0;
}
int main(int argc, char* argv[]) {
  int i, j, n;
  scanf("%d", &n);
  for (i = 0; i < n; i++) {
    scanf("%d", &array[i]);
    sorted[i] = array[i];
  }
  for (i = 0; i < n; i++) {
    int min = sorted[i];
    int min_pos = i;
    for (j = i + 1; j < n; j++) {
      if (min > sorted[j]) {
        min = sorted[j];
        min_pos = j;
      }
    }
    if (min_pos != i) {
      swap(&sorted[i], &sorted[min_pos]);
    }
  }
  printf("%d\n", greedy(n));
  return 0;
}
