#include <bits/stdc++.h>
using namespace std;
template <class P, class Q>
inline void smin(P &a, Q b) {
  if (b < a) a = b;
}
template <class P, class Q>
inline void smax(P &a, Q b) {
  if (a < b) a = b;
}
const long long inf = (long long)1e17;
const int maxd = 1000000 + 100;
const int maxn = 100000 + 100;
int n, m, k;
vector<pair<int, int> > fs[maxd], ts[maxd];
int cf[maxd];
long long mf[maxd];
int ct[maxd];
long long mt[maxd];
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(0);
  cin >> n >> m >> k;
  k++;
  for (int i = 0, i__n = (int)(m); i < i__n; ++i) {
    int d, f, t, c;
    cin >> d >> f >> t >> c;
    d--, f--, t--;
    if (t == -1)
      fs[d].push_back(pair<int, int>(f, c));
    else
      ts[d].push_back(pair<int, int>(t, c));
  }
  memset(cf, -1, sizeof cf);
  int cntf = 0;
  long long curf = 0;
  for (int d = 0, d__n = (int)(maxd); d < d__n; ++d) {
    for (pair<int, int> p : fs[d])
      if (cf[p.first] == -1)
        cntf++, cf[p.first] = p.second, curf += cf[p.first];
      else
        curf -= cf[p.first], smin(cf[p.first], p.second), curf += cf[p.first];
    if (cntf == n)
      mf[d] = curf;
    else
      mf[d] = inf;
  }
  memset(ct, -1, sizeof ct);
  int cntt = 0;
  long long curt = 0;
  for (int d = (int)(maxd), d__a = (int)(0); d-- > d__a;) {
    for (pair<int, int> p : ts[d])
      if (ct[p.first] == -1)
        cntt++, ct[p.first] = p.second, curt += ct[p.first];
      else
        curt -= ct[p.first], smin(ct[p.first], p.second), curt += ct[p.first];
    if (cntt == n)
      mt[d] = curt;
    else
      mt[d] = inf;
  }
  long long ans = inf;
  for (int d = 0, d__n = (int)(maxd - k); d < d__n; ++d)
    smin(ans, mf[d] + mt[d + k]);
  cout << (ans == inf ? -1 : ans) << endl;
  return 0;
}
