#define _CRT_SECURE_NO_WARNINGS
#define _USE_MATH_DEFINES
#include<stdio.h>
#include<stdlib.h>
typedef struct {
	int num;
	int index;
}W;
int main() {
	int  n, i, j, jMin, min, cost = 0, iTmp, tmp,max;
	W w[1000],c;
	scanf("%d", &n);

	for (i = 0; i < n; i++) {
		scanf("%d", &w[i].num);
		if (i == 0)max = w[i].num;
		else if (max < w[i].num) max = w[i].num;
	}
	for (j=n-1; max >= 0; max--) {
		for (i = 0; i < n; i++) {
			if (max == w[i].num) {
				w[i].index = j;
				j--;
			}
		}
	}
	
	for (i = 0; i < n-1; i++) {
		//if (w[i].index == i)continue;
		min = w[i].index;
		jMin = i;
		for (j = i; j < n; j++) {
			if(min>w[j].index){
				min = w[j].index;
				jMin = j;
			}
		}
		if (i != jMin) {
			for (j = 0; j < n; j++) if (jMin == w[j].index) iTmp = j;
			c = w[iTmp]; w[iTmp] = w[jMin]; w[jMin] = c;
			cost += w[iTmp].num + w[jMin].num;
		}
	}
	printf("%d\n", cost);
	
	return 0;
}