#include <bits/stdc++.h>
using namespace std;
template <class T>
void dbg(const char* xn, T x) {
  if (0) cout << xn << ": " << x << "\n";
}
template <class T, class... TA>
void dbg(const char* xn, T x, TA... t) {
  while (*xn != ',')
    if (0) cout << *xn++;
  if (0) cout << ": " << x << ",";
  dbg(xn + 1, t...);
}
template <class T>
inline bool upd_max(T& x, T y) {
  return y > x ? x = y, true : false;
}
template <class T>
inline bool upd_min(T& x, T y) {
  return y < x ? x = y, true : false;
}
const int N = 200007;
const int M = 1000007;
long long n, m, K, mnArrival[N], mnDeparture[N], allArrivals[M],
    allDepartures[M];
long long haveArrivals[M], haveDepartures[M];
vector<pair<long long, long long> > arrivals[M], departures[M];
void preprocess() {
  for (long long i = 1; i <= (n); ++i)
    mnArrival[i] = mnDeparture[i] = 1000000007LL;
  long long mnTotal = 1000000007LL * n;
  for (long long day = 1; day <= M - 5; ++day) {
    haveArrivals[day] = haveArrivals[day - 1];
    for (auto x : arrivals[day]) {
      long long from = x.first;
      long long cost = x.second;
      if (mnArrival[from] == 1000000007LL) ++haveArrivals[day];
      if (cost < mnArrival[from]) {
        mnTotal += cost - mnArrival[from];
        upd_min(mnArrival[from], cost);
      }
    }
    allArrivals[day] = mnTotal;
  }
  mnTotal = 1000000007LL * n;
  for (long long day = M - 5; day >= 1; --day) {
    haveDepartures[day] = haveDepartures[day + 1];
    for (auto x : departures[day]) {
      long long to = x.first;
      long long cost = x.second;
      if (mnDeparture[to] == 1000000007LL) ++haveDepartures[day];
      if (cost < mnDeparture[to]) {
        mnTotal += cost - mnDeparture[to];
        upd_min(mnDeparture[to], cost);
      }
    }
    allDepartures[day] = mnTotal;
  }
}
void findOptimal() {
  if (0)
    if (0) cout << '\n';
  if (0)
    if (0) cout << '\n';
  long long rst = 1000000000000000007LL;
  for (long long i = 1; i <= M - 5 - K; ++i) {
    long long nv = allArrivals[i - 1] + allDepartures[i + K + 1 - 1];
    if (haveArrivals[i - 1] == n && haveDepartures[i + K + 1 - 1] == n)
      upd_min(rst, nv);
  }
  cout << (rst < n * 1000000007LL ? rst : -1);
}
void solve() {
  cin >> n >> m >> K;
  for (long long i = 0; i < m; ++i) {
    long long day, from, to, cost;
    cin >> day >> from >> to >> cost;
    if (from == 0)
      departures[day].emplace_back(to, cost);
    else
      arrivals[day].emplace_back(from, cost);
  }
  preprocess();
  findOptimal();
}
int32_t main() {
  ios_base::sync_with_stdio(0);
  cin.tie(NULL);
  cout << fixed << setprecision(10);
  solve();
  return 0;
}
