#include #include #include #include using namespace std; struct edge { int to, cap, rev; }; const int inf = 1012345678; int N, M, V, d, a[1009], b[1009], p[1009], q[1009], w[1009], ps[1009]; bool vis[2009]; vector t[1009]; vector g[2009]; void add_edge(int v1, int v2, int cost) { g[v1].push_back(edge{ v2, cost, (int)g[v2].size() }); g[v2].push_back(edge{ v1, 0, (int)g[v1].size() - 1 }); } int find_augment(int pos, int tar, int curflow) { if (pos == tar) return curflow; vis[pos] = true; for (edge &e : g[pos]) { if (!vis[e.to] && e.cap > 0) { int newflow = find_augment(e.to, tar, min(e.cap, curflow)); if (newflow > 0) { e.cap -= newflow; g[e.to][e.rev].cap += newflow; return newflow; } } } return 0; } long long max_flow(int src, int dst) { long long ret = 0; while (true) { fill(vis, vis + V, false); int res = find_augment(src, dst, inf); if (res == 0) break; ret += res; } return ret; } int main() { cin >> N >> M >> d; t[0] = { 0 }; t[N - 1] = { inf }; for (int i = 0; i < M; i++) { cin >> a[i] >> b[i] >> p[i] >> q[i] >> w[i]; t[--a[i]].push_back(p[i]); t[--b[i]].push_back(q[i] + d); } 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()); ps[i + 1] = ps[i] + t[i].size(); for (int j = ps[i]; j < ps[i + 1] - 1; j++) { add_edge(j, j + 1, inf); } } for (int i = 0; i < M; i++) { int pa = lower_bound(t[a[i]].begin(), t[a[i]].end(), p[i]) - t[a[i]].begin() + ps[a[i]]; int pb = lower_bound(t[b[i]].begin(), t[b[i]].end(), q[i] + d) - t[b[i]].begin() + ps[b[i]]; add_edge(pa, pb, w[i]); } V = ps[N]; long long ret = max_flow(0, V - 1); cout << ret << '\n'; return 0; }