import std.array, std.stdio, std.conv, std.string, std.math, std.random, std.range,std.functional;
import std.algorithm.searching, std.algorithm.sorting, std.algorithm.iteration, std.algorithm.comparison;
 
long count;
 
void main()
{
    readln();
    int[] list = readln().split.to!(int[]);
    auto sortedList = list.dup.sort();

    bool[] bList;
    long[][] cycleList;
    bList.length = list.length;

    foreach(i; 0..list.length)
    {
        if(bList[i])
            continue;
        long nextIndex = i;
        long[] cycle;
        while(true)
        {
            bList[nextIndex] = true;
            cycle ~= list[nextIndex];
            nextIndex = sortedList.countUntil(list[nextIndex]);
            if(i == nextIndex)
                break;
        }
        cycleList ~= cycle;
    }
    long min = sortedList[0];
    foreach(c; cycleList)
    {
        long cMin = c.reduce!"a<b?a:b";
        long a = cMin * (c.length - 2) + c.sum();
        long b = min * (c.length - 1) + c.sum() - cMin + (min+cMin)*2;
        count += a<b?a:b;
    }
    writeln(count);
}
 
sizediff_t minIndex(alias pred="a<b", R) (R list)
    if(isForwardRange!R && !isInfinite!R && is(typeof(binaryFun!pred(list.front, list.front))))
{
    assert(!list.empty);
    typeof(list.front) min = list.front;
    sizediff_t minPos;
    sizediff_t curPos;
    for(list.popFront(); !list.empty; list.popFront())
    {
        curPos++;
 
        if(binaryFun!pred(list.front, min))
        {
            min = list.front;
            minPos = curPos;
        }
    }
    return minPos;
}

