gets
w=gets.split.map.with_index{|l,i|[l.to_i,i]}
w.sort_by{|l|l[0]}.map.with_index{|l,i|w[w.index l]<<i}
c=0
w.map{|l|_,a,b=l
a==b&&next
q=*a
(m=w.find{|m|b==m[1]}
_,a,b=m
q<<a)while q[0]!=b
s=q.map{|r|w[r][2]=r
w[r][0]}.sort
c+=s.shift*s.size+s.reduce(:+)}
p c