#include <bits/stdc++.h>
using namespace std;
template <typename T>
inline bool chkmin(T &a, const T &b) {
  return a > b ? a = b, 1 : 0;
}
template <typename T>
inline bool chkmax(T &a, const T &b) {
  return a < b ? a = b, 1 : 0;
}
template <typename T>
inline bool smin(T &a, const T &b) {
  return a > b ? a = b : a;
}
template <typename T>
inline bool smax(T &a, const T &b) {
  return a < b ? a = b : a;
}
const long long N = (long long)2e6 + 6, mod = (long long)0, oo = 1e11 + 100;
long long best[N], pre[N], suf[N];
vector<pair<long long, long long>> arrive[N], depart[N];
int32_t main() {
  long long n, m, k;
  cin >> n >> m >> k;
  for (long long j = 0; j < m; ++j) {
    long long d, f, t, c;
    cin >> d >> f >> t >> c;
    if (f == 0) {
      depart[d].push_back(make_pair(--t, c));
    } else {
      arrive[d].push_back(make_pair(--f, c));
    }
  }
  {
    for (long long j = 0; j < n; ++j) best[j] = oo;
    long long sum = n * oo;
    for (long long day = 0; day < N; ++day) {
      for (auto first : arrive[day]) {
        long long dif = max(0LL, best[first.first] - first.second);
        best[first.first] = min(best[first.first], first.second);
        sum -= dif;
      }
      pre[day] = sum;
    }
  }
  {
    for (long long j = 0; j < n; ++j) best[j] = oo;
    long long sum = n * oo;
    for (long long day = N - 1; day >= 0; --day) {
      for (auto first : depart[day]) {
        long long dif = max(0LL, best[first.first] - first.second);
        best[first.first] = min(best[first.first], first.second);
        sum -= dif;
      }
      suf[day] = sum;
    }
  }
  long long res = oo;
  for (long long day = 0; day < N - k - 1; ++day) {
    res = min(res, pre[day] + suf[day + k + 1]);
  }
  if (res >= oo) {
    res = -1;
  }
  cout << res << '\n';
}
