#include #define ll long long #define REP(i, n) for (ll i = 0, max_i = (n); i < max_i; i++) #define REPI(i, a, b) for (ll i = (a), max_i = (b); i < max_i; i++) #define ALL(obj) (obj).begin(), (obj).end() #define RALL(obj) (obj).rbegin(), (obj).rend() #define fi first #define se second #define pb push_back #define debug(x) cerr << #x << ": " << (x) << endl #define debug2(x, y) cerr << #x << ": " << (x) << " " << #y << ": " << y << endl; #define int long long using namespace std; using II = pair; using VII = vector; using VI = vector; using VVI = vector; using VVVI = vector; template inline T in() { T x; cin >> x; return x; } template inline bool chmax(T &a, const T &b) { if (a < b) { a = b; return true; } return false; } template inline bool chmin(T &a, const T &b) { if (a > b) { a = b; return true; } return false; } template ostream& operator<<(ostream &s, const vector& d) { int n = d.size(); REP (i, n) s << d[i] << " "; return s; } template ostream& operator<<(ostream &s, const vector>& dd) { for (vector d: dd) s << d << endl; return s; } struct Fast { Fast() { cin.tie(0); ios::sync_with_stdio(false); } } fast; const int MOD = 1e9 + 7; // Dinic法 class Graph { VI level, iter; void bfs(int s) { for (int i = 0; i < level.size(); i++) level[i] = -1; queue que; level[s] = 0; que.push(s); while (!que.empty()) { int v = que.front(); que.pop(); for (int i = 0; i < G[v].size(); i++) { edge &e = G[v][i]; if (e.cap > 0 && level[e.to] < 0) { level[e.to] = level[v] + 1; que.push(e.to); } } } } int dfs(int v, int t, int f) { if (v == t) return f; for (int &i = iter[v]; i < G[v].size(); i++) { edge &e = G[v][i]; if (e.cap > 0 && 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; } public: int V; struct edge {int to, cap, rev; }; vector> G; Graph(int V) : V(V), G(V), level(V), iter(V) {} void add_edge(int from, int to, int cap) { G[from].push_back(edge{ to, cap, (int)G[to].size() }); G[to].push_back(edge{ from, 0, (int)G[from].size() - 1 }); } int max_flow(int s, int t) { int flow = 0; while (1) { bfs(s); if (level[t] < 0) return flow; for (int i = 0; i < iter.size(); i++) iter[i] = 0; int f; while ((f = dfs(s, t, (1LL << 60))) > 0) { flow += f; } } } }; struct Flight { int u, v, p, q, w; }; signed main() { int N, M, d; cin >> N >> M >> d; map trans; vector flights(M); REP (i, M) { int u, v, p, q, w; cin >> u >> v >> p >> q >> w; q += d; flights[i] = {u, v, p, q, w}; trans[{u, p}]; trans[{v, q}]; } int k = 0; for (auto& p: trans) { p.se = k++; } Graph g(k); for (Flight f: flights) { g.add_edge(trans[{f.u, f.p}], trans[{f.v, f.q}], f.w); } for (auto it = trans.begin(); it != prev(trans.end()); it++) { if (next(it)->fi.fi == it->fi.fi) { g.add_edge(it->se, next(it)->se, 1e18); } } cout << g.max_flow(0, k - 1) << endl; }