gets
w=gets.split.map.with_index{|l,i|[l.to_i,i]}
x=w.sort_by{|l|l[0]}
x.map.with_index{|l,i|w[w.index l]<<i}
c=0
w.map{|l|_,a,b=l
a==b&&next
q=*a
(_,a,b=w.find{|k|b==k[1]}
q<<a)while q[0]!=b
s=q.map{|r|w[r][2]=r
w[r][0]}
t=s.reduce:+
c+=[t+s[-1]+x[0][0]*z=-~s.size,t+s[-1]*(z-3)].min}
p c