//?????´???????????????????°???????????????´????????¬??\????????¨??????????????????
#include<stdio.h>
#include<limits.h>

void swap(int *a, int *b){
	int temp = *a;
	*a = *b;
	*b = temp;
	return;
}

void merge(int A[], int left, int mid, int right){
	int n1 = mid - left;
	int n2 = right - mid;
	int L[n1+1], R[n2+1];
	int i, j, k;
	for( i = 0; i < n1; i++ ){ L[i] = A[left+i]; }
	for( i = 0; i < n2; i++ ){ R[i] = A[mid+i]; }
	L[n1] = INT_MAX;
	R[n2] = INT_MAX;
	i = 0;
	j = 0;
	for( k = left; k < right; k++ ){
		if( L[i] <= R[j] ){
			A[k] = L[i++];
		}else{
			A[k] = R[j++];
		}
	}
	return;
}

void mergeSort(int A[], int left, int right){
	if( left+1 <  right ){
		int mid = (left + right) / 2;
		mergeSort(A, left, mid);
		mergeSort(A, mid, right);
		merge(A, left, mid, right);
	}
	return;
}

int minimumCostSort(int A[], int sorted[], int n){
	int i, j;
	int min, minj, target, targetj;
	int cost = 0;
	for( i = 0; i < n; i++ ){
		min = sorted[i];
		//sorted???i?????????????´????A??????????????????(minj)????????????
		for( j = 0; j < n; j++ ){
			if( A[j] == min ){
				minj = j;
				break;
			}
		}
		while( minj != i ){
			target = sorted[minj];
			for( j = 0; j < n; j++ ){
				if( A[j] == target ){
					targetj = j;
					break;
				}
			}
			cost += A[minj] + A[targetj];
			swap(&A[minj], &A[targetj]);
			minj = targetj;
		}
	}
	return cost;
}

int main(){
	int n, i;
	int w[1000], sorted[1000];
	scanf("%d", &n);
	for( i = 0; i < n; i++ ){
		scanf("%d", &w[i]);
		sorted[i] = w[i];
	}
	mergeSort(sorted, 0, n);
	printf("%d\n", minimumCostSort(w, sorted, n));
	return 0;
}