#include #include #include #include #include template class maxflow { struct edge {int to, rep; T cap;}; std::vector> g; std::vector dis, id; public: maxflow(int n) : g(n), id(n), dis(n) {} void add(int s, int t, T f) { g[s].push_back({t, g[t].size(), f}); g[t].push_back({s, g[s].size() - 1, 0}); } T flow(int s, int t) { T ret = 0; while (true) { bfs(s); if (dis[t] <= dis[s]) return ret; id.assign(id.size(), 0); T val; while ((val = path(s, t)) > 0) ret += val; } } private: void bfs(int s) { dis.assign(g.size(), -1); dis[s] = 0; std::queue q; for (q.push(s); !q.empty(); q.pop()) { int now = q.front(); for (auto &v : g[now]) { if (v.cap > 0 && dis[v.to] < 0) { dis[v.to] = dis[now] + 1; q.push(v.to); } } } } T path(int s, int t) { const T inf = ((1LL << 60) | (1 << 30)); std::stack st; T ret = inf; st.push({s, -1, inf}); while (!st.empty()) { auto now = st.top(); st.pop(); if (now.rep == -1) { if (now.to == t) { ret = now.cap; break; } for (int &i = id[now.to]; i < g[now.to].size(); ++i) { auto &e = g[now.to][i]; if (dis[e.to] > dis[now.to] && e.cap > 0) { st.push({e.to, e.rep, 0}); st.push({e.to, -1, std::min(e.cap, now.cap)}); } } } } if (ret == inf) return 0; int now = t; while (now != s) { while (!st.empty() && st.top().to != now) st.pop(); edge &v1 = st.top(), &v2 = g[v1.to][v1.rep]; v2.cap += ret; g[v2.to][v2.rep].cap -= ret; now = v2.to; } return ret; } }; using namespace std; int main() { const long long inf = 1LL << 60; int n, m, d; cin >> n >> m >> d; vector u(m), v(m), p(m), q(m), w(m); vector> t(n); for (int i = 0; i < m; ++i) { cin >> u[i] >> v[i] >> p[i] >> q[i] >> w[i]; --u[i], --v[i]; t[u[i]].push_back(p[i]); t[v[i]].push_back(q[i] + d); } t[0].push_back(0); t[n - 1].push_back(2e9); for (int i = 0; i < n; ++i) { sort(t[i].begin(), t[i].end()); t[i].erase(unique(t[i].begin(), t[i].end()), t[i].end()); } vector id(n + 1); for (int i = 1; i <= n; ++i) id[i] = id[i - 1] + t[i - 1].size(); maxflow mf(id[n]); for (int i = 0; i < n; ++i) for (int j = 0; j < (int)t[i].size() - 1; ++j) mf.add(id[i] + j, id[i] + j + 1, inf); for (int i = 0; i < m; ++i) { int id1 = lower_bound(t[u[i]].begin(), t[u[i]].end(), p[i]) - t[u[i]].begin(); int id2 = lower_bound(t[v[i]].begin(), t[v[i]].end(), q[i] + d) - t[v[i]].begin(); mf.add(id[u[i]] + id1, id[v[i]] + id2, w[i]); } long long ans = mf.flow(0, id[n] - 1); cout << ans << endl; }