#include using namespace std; #define rep(i,n) for (int (i)=(0);(i)<(int)(n);++(i)) using ll = long long; using P = pair; using namespace std; template void vin(vector& v, int n) { v.resize(n); for (int i = 0; i < n; ++i) { cin >> v[i]; } } template class Dinic { private: const T INF; struct edge { T to, cap, rev; edge(T to, T cap, T rev) :to(to), cap(cap), rev(rev) {} }; T V; vector> g; vector level; // sourceからの距離 vector itr; // どこまで調べ終わったか public: Dinic(T V) :INF(1e9+7), V(V), g(V, vector()) {} void add_edge(T from, T to, T cap) { g[from].emplace_back(to, cap, g[to].size()); g[to].emplace_back(from, 0, g[from].size()-1); } // sourceからの最短路を幅優先で探索 void bfs(T s) { level = vector(V, -1); queue que; que.push(s); level[s] = 0; while (que.size()) { int v = que.front(); que.pop(); for (edge &e : g[v]) { if (e.cap > 0 and level[e.to] < 0) { level[e.to] = level[v] + 1; que.push(e.to); } } } } // v->tの増加路を探す T dfs(T v, T t, T f) { if (v == t) return f; for (T& i = itr[v]; i < g[v].size(); ++i) { edge& e = g[v][i]; if (e.cap > 0 and level[v] < level[e.to]) { int d = dfs(e.to, t, min(f, e.cap)); if (d > 0) { e.cap -= d; g[e.to][e.rev].cap += d; return d; } } } return 0; } T max_flow(T s, T t) { T flow = 0, f; while (true) { bfs(s); if (level[t] < 0) return flow; itr = vector(V, 0); while ((f = dfs(s, t, numeric_limits::max())) > 0) { flow += f; } } } }; ll N, M, d; ll u[1010], v[1010], p[1010], q[1010], w[1010]; ll sz[1010]; vector t[1010]; int main() { cin >> N >> M >> d; rep(i, M) { cin >> u[i] >> v[i] >> p[i] >> q[i] >> w[i]; u[i]--; v[i]--; q[i] += d; t[u[i]].push_back(p[i]); t[v[i]].push_back(q[i]); } rep(i, N) { sort(t[i].begin(), t[i].end()); t[i].erase(unique(t[i].begin(), t[i].end()), t[i].end()); } sz[0] = t[0].size(); for (int i=1; i flow(sz[N-1]); rep(i, N) { int st = 0; if (i) st += sz[i-1]; int n = t[i].size(); rep(j, n-1) flow.add_edge(st+j, st+j+1, 1LL<<60); } rep(i, M) { int a = lower_bound(t[u[i]].begin(), t[u[i]].end(), p[i]) - t[u[i]].begin(); if (u[i] > 0) a += sz[u[i]-1]; int b = lower_bound(t[v[i]].begin(), t[v[i]].end(), q[i]) - t[v[i]].begin(); if (v[i] > 0) b += sz[v[i]-1]; flow.add_edge(a, b, w[i]); } cout << flow.max_flow(0, sz[N-1]-1) << endl; return 0; }