#include using namespace std; #define rep(i, n) for(int i = 0; i < n; i++) #define rep2(i, x, n) for(int i = x; i <= n; i++) #define rep3(i, x, n) for(int i = x; i >= n; i--) #define elif else if #define sp(x) fixed << setprecision(x) #define pb push_back #define eb emplace_back #define all(x) x.begin(), x.end() #define sz(x) (int)x.size() using ll = long long; using ld = long double; using pii = pair; using pil = pair; using pli = pair; using pll = pair; const ll MOD = 1e9+7; //const ll MOD = 998244353; const int inf = (1<<30)-1; const ll INF = (1LL<<60)-1; const ld EPS = 1e-10; template bool chmax(T &x, const T &y) {return (x < y)? (x = y, true) : false;}; template bool chmin(T &x, const T &y) {return (x > y)? (x = y, true) : false;}; template struct Max_Flow{ struct edge{ int to; T cap; int rev; edge(int to, T cap, int rev) : to(to), cap(cap), rev(rev) {} }; vector> es; vector used; const T INF_T; Max_Flow(int n) : INF_T(numeric_limits::max()){ es.resize(n), used.resize(n); } void add_edge(int from, int to, T cap){ es[from].eb(to, cap, sz(es[to])); es[to].eb(from, 0, sz(es[from])-1); } T dfs(int now, int t, T flow){ if(now == t) return flow; used[now] = true; for(auto &e: es[now]){ if(!used[e.to] && e.cap > 0){ T f = dfs(e.to, t, min(flow, e.cap)); if(f > 0){ e.cap -= f; es[e.to][e.rev].cap += f; return f; } } } return 0; } T max_flow(int s, int t){ T flow = 0; for(;;){ fill(all(used), false); T f = dfs(s, t, INF_T); if(f == 0) return flow; flow += f; } } }; int main(){ int N, M, D; cin >> N >> M >> D; int u[M], v[M], p[M], q[M]; ll w[M]; map mp; rep(i, M){ cin >> u[i] >> v[i] >> p[i] >> q[i] >> w[i]; u[i]--, v[i]--, q[i] += D; mp[pii(u[i], p[i])]++, mp[pii(v[i], q[i])]++; } mp[pii(0, 0)]++, mp[pii(N-1, 1000000000+D)]++; int n = 0; pii pre = pii(-1, -1); vector memo; for(auto &e: mp){ if(e.first.first == pre.first) memo.pb(n); e.second = n++; pre = e.first; } Max_Flow G(n); for(auto &e: memo) G.add_edge(e-1, e, INF); rep(i, M){ G.add_edge(mp[pii(u[i], p[i])], mp[pii(v[i], q[i])], w[i]); } cout << G.max_flow(0, n-1) << endl; }