#include <bits/stdc++.h>
using namespace std;
inline long long mod(long long n, long long m) {
  long long ret = n % m;
  if (ret < 0) ret += m;
  return ret;
}
long long gcd(long long a, long long b) {
  return (b == 0LL ? a : gcd(b, a % b));
}
long long exp(long long a, long long b, long long m) {
  if (b == 0LL) return 1LL;
  if (b == 1LL) return mod(a, m);
  long long k = mod(exp(a, b / 2, m), m);
  if (b & 1LL) {
    return mod(a * mod(k * k, m), m);
  } else
    return mod(k * k, m);
}
const long long N = 2e6 + 100;
vector<pair<long long, long long> > sai[N], chega[N];
long long pre[N];
long long suf[N];
bool gp[N], gs[N];
long long cur[N];
const long long inf = 1e9;
int32_t main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  ;
  long long n, m, k;
  cin >> n >> m >> k;
  k++;
  for (long long i = 0; i < m; i++) {
    long long d, f, t, c;
    cin >> d >> f >> t >> c;
    if (f == 0)
      sai[d].push_back(pair<long long, long long>(t, c));
    else
      chega[d].push_back(pair<long long, long long>(f, c));
  }
  for (long long i = 0; i < N; i++) {
    pre[i] = 0;
    cur[i] = inf;
  }
  long long novo = 0;
  for (long long i = 1; i < N; i++) {
    pre[i] = pre[i - 1];
    for (auto ch : chega[i]) {
      long long cid = ch.first;
      long long cost = ch.second;
      if (cost < cur[cid]) {
        if (cur[cid] == inf) novo++;
        if (cur[cid] != inf) pre[i] -= cur[cid];
        pre[i] += cost;
        cur[cid] = cost;
      }
    }
    if (novo == n) gp[i] = 1;
  }
  if (novo != n) {
    cout << -1 << "\n";
    return 0;
  }
  novo = 0;
  for (long long i = 1; i < N; i++) {
    suf[i] = 0;
    cur[i] = inf;
  }
  for (long long i = N - 2; i >= 1; i--) {
    suf[i] = suf[i + 1];
    for (auto w : sai[i]) {
      long long t = w.first;
      long long cost = w.second;
      if (cost < cur[t]) {
        if (cur[t] == inf) novo++;
        if (cur[t] != inf) suf[i] -= cur[t];
        suf[i] += cost;
        cur[t] = cost;
      }
    }
    if (novo == n) gs[i] = 1;
  }
  if (novo != n) {
    cout << -1 << "\n";
    return 0;
  }
  long long best = inf * inf;
  for (long long i = 1; i + k < N; i++) {
    if (gp[i] and gs[i + k]) {
      best = min(best, pre[i] + suf[i + k]);
    }
  }
  if (best >= inf * n) {
    cout << -1 << "\n";
  } else
    cout << best << "\n";
}
