def f(start, last) distances = Edges.dup N.times{|i| N.times{|ii| N.times{|iii| distances[[ii,iii]] = [distances[[ii,iii]], distances[[i,ii]] + distances[[i,iii]]].min } } } N.times.map{|i| next 1.0/0 if i == start || i == last N.times.map{|ii| next 1.0/0 if i == ii || ii == start || ii == last Stays[i] + Stays[ii] + distances[[start,i]] + distances[[i,ii]] + distances[[ii,last]] }.min }.min end N =gets.to_i Stays = N.times.map{gets.to_i} M = gets.to_i Edges = M.times.inject(Hash.new(1.0/0)){|r,i| *from_to, cost = gets.split.map(&:to_i) r[from_to] = cost r[from_to.rotate] = cost r } p f(0, N-1)