n = read_line.to_i c = read_line.to_i v = read_line.to_i graph = Array.new(n) { [] of Tuple(Int32, Int32, Int32) } v.times do s, t, y, m = read_line.split.map(&.to_i) graph[s - 1] << {t - 1, y, m} end INF = 1_000_000_000 dp = Array.new(c + 1, INF) dp[c] = 0 n.times do |i| temp = dp.dup edges = graph[i] c.downto(0) do |k| current_time = temp[k] next if current_time == INF edges.each do |to, cost, time| next if k < cost new_k = k - cost new_time = current_time + time if new_time < dp[new_k] dp[new_k] = new_time end end end end result = dp.min puts result == INF ? -1 : result