def main n = gets.to_i c = gets.to_i v = gets.to_i s = gets.split.map(&:to_i) t = gets.split.map(&:to_i) y = gets.split.map(&:to_i) m = gets.split.map(&:to_i) ways_from = [] v.times do |i| if ways_from[s[i]] ways_from[s[i]] << { next: t[i], cost: y[i], min: m[i] } else ways_from[s[i]] = [{ next: t[i], cost: y[i], min: m[i] }] end end candidates = [{ pos: 1, cost: 0, min: 0 }] res = nil while 0 < candidates.size candidates.sort_by! { |candidate| candidate[:min] } candidate = candidates.shift # もし現在地がゴールだったら終了 if candidate[:pos] == n res = candidate[:min] break end # もし移動先がなかったら終了 next if ways_from[candidate[:pos]].empty? # もしお金が足りなかったら終了 ways_from[candidate[:pos]].each do |next_way| next_cost = candidate[:cost] + next_way[:cost] next if c < next_cost candidates << { pos: next_way[:next], cost: next_cost, min: candidate[:min] + next_way[:min]} end end res || -1 end puts main