You are given $n$ integers $w_i (i = 0, 1, ..., n-1)$ to be sorted in ascending order. You can swap two integers $w_i$ and $w_j$. Each swap operation has a cost, which is the sum of the two integers $w_i + w_j$. You can perform the operations any number of times.

Write a program which reports the minimal total cost to sort the given integers.

Constraints

* $1 \leq n \leq 1,000$
* $0 \leq w_i\leq 10^4$
* $w_i$ are all different

Input

In the first line, an integer $n$ is given. In the second line, $n$ integers $w_i (i = 0, 1, 2, ... n-1)$ separated by space characters are given.

Output

Print the minimal cost in a line.

Examples

Input

5
1 5 3 4 2


Output

7


Input

4
4 3 2 1


Output

10
def minimun_cost_sort(array)
	are_sorted = Array.new(array.size, false)
	sorted_array = array.sort
	cost_sum = 0

	array.each_index do |i|
		next if are_sorted[i]
		index = i
		cycle_sum = 0
		min_value = 10000 # enough large value
		cycle_size = 0
		# ソートされていない値からサイクルを見つけてソート済みとする
		loop do
			# 移動コスト計算に必要な値を算出
			cycle_size += 1
			value = array[index]
			min_value = min_value < value ? min_value : value
			cycle_sum += value

			are_sorted[index] = true
			index = sorted_array.index(value) # ソート後の位置を辿ることでサイクルを見つける
			break if are_sorted[index]
		end
		# サイクル内での最適な移動は数式に落とし込んでいる
		# 移動の最小コスト候補は２通りあるのでそれぞれ計算して比較する
		cost1 = cycle_sum + (cycle_size - 2) * min_value
		cost2 = min_value + cycle_sum + (cycle_size + 1) * cycle_sum
		cost_sum += cost1 < cost2 ? cost1 : cost2
	end
	cost_sum
end

n = STDIN.gets.to_i
array = STDIN.gets.split[0...n].map(&:to_i)
puts minimun_cost_sort(array)