#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>

int SelectionSort(int * array, int N){
    
    int i, j, maxj, tmp, ans;
    ans = 0;
    
    for(i = N-1; i >=0; i--){
        maxj = i;
        for(j = i; j >= 0; j--){
            maxj = array[j] > array[maxj] ? j : maxj;
        }
        if(i != maxj){
            ans += (array[maxj] + array[i]);
            tmp = array[maxj];
            array[maxj] = array[i];
            array[i] = tmp;
            
        }
    }
    return ans;
}


int partition(int *A, int left, int right){
    
    /*pivot??¨?????????????????????????´?????????¶*/
    int pivot = A[right];
    int i = left - 1;
    int j;
    int tmp;
    
    for (j=left; j<right; j++) {
        if (A[j] <= pivot) {
            i = i+1;
            /* A[i] ??¨ A[j] ????????? */
            tmp = A[i];
            A[i] = A[j];
            A[j] = tmp;
        }
    }
    
    /* A[i+1] ??¨ A[r] ????????? */
    tmp = A[i+1];
    A[i+1] = A[right];
    A[right] = tmp;
    
    return i+1;
}

/*
 * *A int type array
 * left?????????A????????????????´??????????
 * right?????????A????????????????´??????????
 */
void quicksort(int * A, int left, int right){
    
    int q;
    if (left < right) {
        q = partition(A, left, right);
        quicksort(A, left, q-1);
        quicksort(A, q+1, right);
    }
    
}


void minimumCostSort(int *A, int n){
    
}


int arraycmp(int * A, int *B, int n){
    int i, rtn=0;
    
    
    for (i=0; i< n; i++) {
        if (A[i] != B[i]) {
            rtn++;
        }
    }
    return rtn;
}

void mkarray(int *A, int *B, int n, int *C){
    int i;
    int j = 0;
    
    for (i=0; i < n; i++) {
        if (A[i] != B[i]) {
            C[j] = A[i];
            j++;
        }
    }
}

int main( ){
    
    int n, m, i, *A, *B, *C, ans;
    
    A = (int*)malloc(sizeof(int)*n);
    B = (int*)malloc(sizeof(int)*n);
    
    
    scanf("%d", &n);
    
    for (i=0; i<n; i++) {
        scanf("%d", &A[i]);
    }
    
    memcpy(B, A, sizeof(int) * n);
    
    quicksort(B, 0, n-1);
    
    m = arraycmp(A, B, n);
    
    if (m == 0) {
        printf("0\n");
        return 0;
    }
    
    C = (int*)malloc(sizeof(int)*m);
    
    mkarray(A, B, n, C);
    
    ans = SelectionSort(C, m);
    
    printf("%d\n", ans);
    
    
    
    free(A);
    free(B);
    free(C);

    
    return 0;
}