#include #define int long long #define endl '\n' #define FOR(i, a, n) for (int i = (a); i < (n); ++i) #define REP(i, n) FOR(i, 0, n) using namespace std; template class Dinic { struct edge { int to, rev; T cap; bool isrev; edge(int t, T c, int r, bool i) : to(t), cap(c), rev(r), isrev(i) {} }; void bfs(int s, int t) { lev.assign(g.size(), -1); queue que; lev[s] = 0; que.emplace(s); while (!que.empty() && lev[t] == -1) { int v = que.front(); que.pop(); for (edge& e : g[v]) { if (lev[e.to] == -1 && e.cap > 0) { lev[e.to] = lev[v] + 1; que.emplace(e.to); } } } } T dfs(int v, int t, T f) { if (v == t) return f; for (int& i = ite[v]; i < g[v].size(); ++i) { edge& e = g[v][i]; if (e.cap > 0 && lev[v] < lev[e.to]) { T 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; } public: const T INF; vector lev, ite; vector> g; Dinic(int n) : INF(numeric_limits::max()), g(n) {} void add_edge(int f, int t, T c = numeric_limits::max()) { g[f].emplace_back(t, c, g[t].size(), false); g[t].emplace_back(f, 0, g[f].size() - 1, true); } T max_flow(int s, int t) { T res = 0; while (1) { bfs(s, t); if (lev[t] < 0) break; ite.assign(g.size(), 0); T f = 0; while ((f = dfs(s, t, INF)) > 0) { res += f; } } return res; } void print() { for (int i = 0; i < g.size(); ++i) { for (auto& e : g[i]) { if (e.isrev) continue; auto& rev_e = g[e.to][e.rev]; cout << i << " -> " << e.to << " (flow: " << rev_e.cap << "/" << e.cap + rev_e.cap << ")" << endl; } } } }; const int LIM = 1000000000; int N, M, d; int u[1000], v[1000], p[1000], q[1000], w[1000]; map, int> mp; vector ts[1000]; signed main() { ios::sync_with_stdio(false); cin.tie(nullptr); cin >> N >> M >> d; mp[make_pair(0, 0)]++; mp[make_pair(N - 1, LIM)]++; ts[0].push_back(0); ts[N - 1].push_back(LIM); REP (i, M) { cin >> u[i] >> v[i] >> p[i] >> q[i] >> w[i]; u[i]--; v[i]--; mp[make_pair(u[i], p[i])]++; mp[make_pair(v[i], min(q[i] + d, LIM))]++; ts[u[i]].push_back(p[i]); ts[v[i]].push_back(min(q[i] + d, LIM)); } int num = 0; for (auto&& p : mp) p.second = num++; Dinic g(num); REP (i, N) { sort(ts[i].begin(), ts[i].end()); ts[i].erase(unique(ts[i].begin(), ts[i].end()), ts[i].end()); REP (j, (int)ts[i].size() - 1) { int a = mp[make_pair(i, ts[i][j])]; int b = mp[make_pair(i, ts[i][j + 1])]; g.add_edge(a, b); } } REP (i, M) { int a = mp[make_pair(u[i], p[i])]; int b = mp[make_pair(v[i], min(q[i] + d, LIM))]; g.add_edge(a, b, w[i]); } int s = mp[make_pair(0, 0)]; int t = mp[make_pair(N - 1, LIM)]; cout << g.max_flow(s, t) << endl; }