from collections import deque class Dinic: def __init__(self, n): self.n = n self.links = [[] for _ in range(n)] self.depth = None self.progress = None def add_link(self, _from, to, cap): self.links[_from].append([cap, to, len(self.links[to])]) self.links[to].append([0, _from, len(self.links[_from]) - 1]) def bfs(self, s): depth = [-1] * self.n depth[s] = 0 q = deque([s]) while q: v = q.popleft() for cap, to, rev in self.links[v]: if cap > 0 and depth[to] < 0: depth[to] = depth[v] + 1 q.append(to) self.depth = depth def dfs(self, v, t, flow): if v == t: return flow links_v = self.links[v] for i in range(self.progress[v], len(links_v)): self.progress[v] = i cap, to, rev = link = links_v[i] if cap == 0 or self.depth[v] >= self.depth[to]: continue d = self.dfs(to, t, min(flow, cap)) if d == 0: continue link[0] -= d self.links[to][rev][0] += d return d return 0 def max_flow(self, s, t): flow = 0 while True: self.bfs(s) if self.depth[t] < 0: return flow self.progress = [0] * self.n current_flow = self.dfs(s, t, float('inf')) while current_flow > 0: flow += current_flow current_flow = self.dfs(s, t, float('inf')) n, m, d = map(int, input().split()) Q = [[] for _ in range(n)] Q[0].append(-1) Q[-1].append(1 << 60) E = [] for _ in range(m): u, v, p, q, w = map(int, input().split()) q += d u -= 1 v -= 1 E.append((u, v, p, q, w)) Q[u].append(p) Q[v].append(q) dic = {} ind = 0 for i in range(n): Q[i].sort() for j in Q[i]: dic[(i, j)] = ind ind += 1 G = Dinic(ind) for u, v, p, q, w in E: G.add_link(dic[(u, p)], dic[(v, q)], w) for i in range(n): if len(Q[i]) == 0: continue b = dic[(i, Q[i][0])] for j in Q[i][1:]: c = dic[(i, j)] G.add_link(b, c, 1 << 60) b = c ans = G.max_flow(0, ind - 1) print(ans)