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 <stdio.h>

#define NMAX 1000
#define WMAX 10000

int mincost(short *, int, int);

int main(){

  int i, j, n, d, wtemp, wmin=WMAX, cost=0;
  short w[NMAX], s[NMAX], l[NMAX];
  char c[WMAX+1]={0}, flag[NMAX]={0};

  scanf("%d",&n);

  for (i=0; i<n; i++) {
    scanf("%d",&w[i]);
    if (wmin > w[i]) wmin = w[i];
    c[w[i]]++;
  }

  j=0;

  for (i=0; i<=WMAX; i++) {
    if(c[i]) {
      s[j] = i;
      j++;
    }
  }

  for (i=0; i<n; i++) {
    if( flag[i]==0 ) {
      d = 0;
      flag[i]++;
      l[d] = w[i];
      d++;
      wtemp = w[i];
      while (1) {
        j = 0;
        while (s[j] != wtemp) j++;
        if(j == i) break;
        flag[j]++;
        l[d] = w[j];
        d++;
        wtemp = w[j];
      }
      cost += mincost(l, d, wmin);
    }
  }

  printf("%d\n",cost);

  return 0;
}

int mincost(short *l, int d, int wmin)
{
    int i, c1=0, c2, lmin=WMAX, imin;

    for (i=0; i<d; i++) {
        c1 += l[i];
        if(lmin > l[i]) {
            lmin = l[i];
        }
    }

    c2 = c1;
    c1 += (d-2)*lmin;
    c2 += lmin + (d+1)*wmin;

    if (c1 < c2) return c1;
    else return c2;
}