INF = 10 ** 15 class Graph Edge = Struct.new(:to, :cap, :rev) def size; @g.size; end def _min(a,b); a < b ? a : b; end def initialize(n); @g = Array.new(n){ [] }; end def add_edge(from, to, cap) fwd, rev = @g[from].size, @g[to].size @g[from] << Edge.new(to, cap, rev) @g[to] << Edge.new(from, 0, fwd) self end def max_flow(s,t) flow = 0 while level = levelize(s,t) active = Array.new(size, 0) while f = find_flow(s, t, level, active) flow += f end end flow end def find_flow(s, t, level, active) parent = Array.new(size) parent[s] = s u = s until u == t if (j = active[u]) >= @g[u].size break if u == s u = parent[u] active[u] += 1 else e = @g[u][j] if e.cap > 0 && level[e.to] < level[u] parent[e.to] = u u = e.to else active[u] += 1 end end end return nil if u == s f = INF u = s until u == t e = @g[u][active[u]] f = _min(e.cap, f) u = e.to end u = s until u == t fwd = @g[u][active[u]] rev = @g[fwd.to][fwd.rev] fwd.cap -= f rev.cap += f u = fwd.to end return f end def levelize(s,t) level = Array.new(size, @g.size * 2) level[t] = 0 q = [t] until q.empty? u = q.shift d = level[u] @g[u].each do |e| if @g[e.to][e.rev].cap > 0 && level[e.to] > d + 1 level[e.to] = d + 1 q << e.to end end end level[s] = @g.size if level[s] <= @g.size level[s] <= @g.size ? level : nil end end Line = Struct.new(:id, :u, :v, :s, :t, :w) do def from; 2 * id; end def to; 2 * id + 1; end end N,M,d = gets.split.map(&:to_i) S = 2 * M; T = 2 * M + 1; G = Graph.new(2 * M + 2) L = M.times.map{|id| u,v,s,t,w = gets.split.map(&:to_i); Line.new(id,u,v,s,t,w) } L.each do |l| G.add_edge(l.from, l.to, l.w) G.add_edge(S, l.from, INF) if l.u == 1 G.add_edge(l.to, T, INF) if l.v == N end L.each do |l| L.each do |r| next if l.v != r.u G.add_edge(l.to, r.from, INF) if l.t + d <= r.s end end puts G.max_flow(S, T)