let inputString = '';

process.stdin.on('data', inputStdin => {
    inputString += inputStdin;
});
process.stdin.on('end', function() {
    const input = inputString.replace(/\s*$/, '')
        .split('\n')
        .map(str => str.replace(/\s*$/, ''));

    const nums = input[1].split(' ').map(s => Number(s));

    console.log(minCost(nums));
});

const MAX = 1000; // Max length of the array
const VMAX = 10000; // Max volume of the stuff

const minCost = (arr) => {
  let answer = 0;

  const minimumWeightInAll = Math.min(...arr);
  const sorted = [...arr].sort((a, b) => a - b);
  const isUsedInLoops = new Array(arr.length).fill(false);
  
  const weightSortedIndexMap = new Array(VMAX + 1);
  for (let i=0; i<sorted.length; i++) {
    weightSortedIndexMap[sorted[i]] = i;
  }

  for (let i=0; i<arr.length; i++) {
    if (isUsedInLoops[i]) {
      continue;
    }

    let currentIndex = i;
    let sumWeightInLoop = 0;
    let minimumWeightInLoop = VMAX; // will be the base of swappings
    let elementNumInCurrentLoop = 0;
    while (true) {
      isUsedInLoops[currentIndex] = true;
      elementNumInCurrentLoop++;
      const v = arr[currentIndex];

      minimumWeightInLoop = Math.min(minimumWeightInLoop, v);

      sumWeightInLoop += v;

      currentIndex = weightSortedIndexMap[v];
      if (isUsedInLoops[currentIndex]) {
        break;
      }
    }
    // swapping only in the loop
    const costInLoop = sumWeightInLoop + (elementNumInCurrentLoop - 2) * minimumWeightInLoop;
    // swapping with the num out of the loop
    const costWithNumOutOfLoop = sumWeightInLoop + minimumWeightInLoop  + (elementNumInCurrentLoop + 1) * minimumWeightInAll;
    answer += Math.min(costInLoop, costWithNumOutOfLoop);
  }

  return answer;
};
