#include <bits/stdc++.h>
using namespace std;
template <typename _T>
inline void _DBG(const char *s, _T x) {
  cerr << s << " = " << x << "\n";
}
template <typename _T, typename... args>
void _DBG(const char *s, _T x, args... a) {
  while (*s != ',') cerr << *s++;
  cerr << " = " << x << ',';
  _DBG(s + 1, a...);
}
const int N = 1e6 + 7;
const long long INF = 1e13 + 7;
int n, m, k;
long long mn[N], pre[N], suf[N];
vector<pair<int, int> > G[2][N];
int main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  cin >> n >> m >> k;
  int M = 0;
  for (int i = 0; i < m; i++) {
    int d, a, b, c;
    cin >> d >> a >> b >> c;
    if (b == 0) {
      G[0][d].push_back({a, c});
    } else {
      G[1][d].push_back({b, c});
    }
    M = max(M, d);
  }
  for (int i = 1; i <= n; i++) mn[i] = INF;
  long long cost = (long long)n * INF;
  for (int i = 1; i <= M; i++) {
    for (auto x : G[0][i]) {
      if (x.second < mn[x.first])
        cost += x.second - mn[x.first], mn[x.first] = x.second;
    }
    pre[i] = cost;
  }
  for (int i = 1; i <= n; i++) mn[i] = INF;
  cost = (long long)n * INF;
  for (int i = M; i; i--) {
    for (auto x : G[1][i]) {
      if (x.second < mn[x.first])
        cost += x.second - mn[x.first], mn[x.first] = x.second;
    }
    suf[i] = cost;
  }
  long long res = (long long)n * INF;
  for (int i = 1; i + k + 1 <= M; i++) res = min(res, pre[i] + suf[i + k + 1]);
  if (res >= INF)
    cout << "-1\n";
  else
    cout << res << "\n";
  return 0;
}
