#include<stdio.h>

#define W_MAX 1000001
#define MAX 1001

int array[MAX];
int sorted[MAX];

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

int greedy(int n){
  int i, j;
  int min = W_MAX, min_pos = -1;
  int next = -1, next_pos = -1;

  int addition = 0;
  for(i = 0; i < n; i++){
    if(array[i] == 0){ continue; }

    for(j = i + 1; j < n; j++){
      if(array[j] == 0) { continue; }

      if(sorted[i] == array[j] && sorted[j] == array[i]){
	swap(&array[i], &array[j]);
	addition += (array[i] + array[j]);
      }
    }
  }

  for(i = 0; i < n; i++){
    if(array[i] == 0 || sorted[i] != array[i] && min > array[i]){
      min = array[i];
      min_pos = i;
    }
  }

  if(min_pos == -1){
    return addition;
  }

  if(min == 0 && min_pos == 0){
    next = W_MAX;
    
    for(i = 0; i < n; i++){
      if(i != min_pos && sorted[i] != array[i] && next > array[i]){
	next = array[i];
	next_pos = i;
      }
    }
  }else{
    next = sorted[min_pos];
    
    for(i = 0; i < n; i++){
      if(array[i] == next){
	next_pos = i;
	break;
      }
    }
  }

  if(next_pos == -1){
    return addition;
  }

  swap(&array[min_pos], &array[next_pos]);
  /*
  for(i = 0; i < n; i++){
    printf("%s%d", i == 0 ? "" : " ", array[i]);
  }
  printf("\n");
  */
  return (next + min) + greedy(n) + addition;
}

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;
}