#include using namespace std; #define rep(i, n) for(int i = 0; i < int(n); i++) using ll = long long; using P = pair; // Ford-Fulkerson template class max_flow { public: struct edge { int to; T cap; int rev; }; int n; vector> g; vector used; max_flow(int n = 0) : n(n), g(n), used(n) { } void add_edge(int from, int to, T cap) { g[from].push_back((edge){to, cap, int(g[to].size())}); g[to].push_back((edge){from, 0LL, int(g[from].size() - 1)}); } T dfs(int v, int goal_v, T flow) { if(v == goal_v) return flow; used[v] = true; for(int i = 0; i < (int)g[v].size(); i++) { edge &e = g[v][i]; if(!used[e.to] && e.cap > 0) { T next_flow = dfs(e.to, goal_v, min(flow, e.cap)); if(next_flow > 0) { e.cap -= next_flow; g[e.to][e.rev].cap += next_flow; return next_flow; } } } return 0; } T calc(int s, int t, T ma = numeric_limits::max()) { T flow = 0; while(1) { used = vector(n, false); T f = dfs(s, t, ma); if(f == 0) return flow; flow += f; } } }; int main() { int n, m, d; cin >> n >> m >> d; vector u(m), v(m), p(m), q(m); vector w(m); rep(i, m) cin >> u[i] >> v[i] >> p[i] >> q[i] >> w[i]; rep(i, m) u[i]--, v[i]--, q[i] += d; vector> g(n); rep(i, m) { g[u[i]].push_back(p[i]); g[v[i]].push_back(q[i]); } g[0].push_back(0); g[n - 1].push_back(2e9 + 1); rep(i, n) sort(g[i].begin(), g[i].end()); rep(i, n) g[i].erase(unique(g[i].begin(), g[i].end()), g[i].end()); vector sum(n + 1); rep(i, n) sum[i + 1] = sum[i] + g[i].size(); ll INF = 1e13; max_flow mf(sum[n]); rep(i, n) { rep(j, g[i].size() - 1) { mf.add_edge(sum[i] + j, sum[i] + j + 1, INF); } } rep(i, m) { int from = sum[u[i]] + (lower_bound(g[u[i]].begin(), g[u[i]].end(), p[i]) - g[u[i]].begin()); int to = sum[v[i]] + (lower_bound(g[v[i]].begin(), g[v[i]].end(), q[i]) - g[v[i]].begin()); mf.add_edge(from, to, w[i]); } cout << mf.calc(0, sum[n] - 1, 1e13) << endl; return 0; }