class Num
  include Comparable
  @@count = 0
  @@sum_weight = 0
  attr_accessor :weight, :position, :right_position
  def initialize(weight)
    @weight = weight
    @position = @@count
    @@count += 1
    @right_position = nil
  end
  
  def <=>(other)
    @weight <=> other.weight
  end
  
  def swap(other)
    @position, other.position = other.position, @position
    @@sum_weight += @weight + other.weight
  end
  
  def inspect
    return [@weight, @position, @right_position]
  end
  
  def move(other)
    if self != other
      swap(other)
      return @position == @right_position
    else
      return true
    end
  end
  
  def self.sum_weight
    return @@sum_weight
  end
end
class String
  def to_n
    return Num.new(self.to_i)
  end
end

def main
  gets
  arr = gets.split(" ").map(&:to_n)
  arr2 = arr.sort
  arr2.each_with_index{|item, idx|item.right_position = idx}
  arr2.each{|item|
    until item.move(arr2[item.position])
    end}
  puts Num.sum_weight
end
main