function createAlignedBaggage(baggage) {
    const aligned = [];
    baggage.forEach(e => aligned[e] = e);
    return aligned.filter(e => e !== undefined);
}

function minimumCostSort(baggage, len, cost, aligned) {
    let min = aligned[len - 1];
    let total = 0;
    let count = 0;

    for (let i = 0; i < len; i++) {
        if (baggage[i] !== aligned[i]) {
            total += baggage[i];
            count++;
            min = baggage[i] < min ? baggage[i] : min;
        }
    }

    const isChangeMin = total + min * count > aligned[0] * (count + 2) + min * 2 + total;

    if(baggage[0] === aligned[0] && isChangeMin){
        const index = baggage.indexOf(min);
        baggage[index] = baggage[0]; // 最小値を現在のminの位置に移動
        baggage[0] = min; // minを一時的に0の位置に移動
        cost[0] += min + baggage[index];
        min = baggage[index];
    }

    if(count) {
        const index = baggage.indexOf(min);
        // minの現在地に本来あるべき要素
        const target = baggage.indexOf(aligned[index]);
        const temp = baggage[target];
        baggage[target] = min;
        baggage[index] = temp;
        cost[0] += min + temp;
        minimumCostSort(baggage, len, cost, aligned);
    }
}

function main(stdin) {
    const input = stdin.split("\n");
    const length = parseInt(input.shift(), 10);
    const baggage = input[0].split(' ').map((e) => parseInt(e, 10));
    const cost = [0];
    const aligned = createAlignedBaggage(baggage);

    minimumCostSort(baggage, length, cost, aligned);
    console.log(cost[0]);
}

main(require("fs").readFileSync("/dev/stdin", "utf8"));

