#include <bits/stdc++.h>
using namespace std;
static inline void canhazfast() {
  ios_base::sync_with_stdio(false);
  cin.tie(nullptr);
  cout.tie(nullptr);
}
template <typename T>
T gcd(T a, T b) {
  return b == 0 ? a : gcd(b, a % b);
}
template <typename T>
T extgcd(T a, T b, T &x, T &y) {
  T x0 = 1, y0 = 0, x1 = 0, y1 = 1;
  while (b) {
    T q = a / b;
    a %= b;
    swap(a, b);
    x0 -= q * x1;
    swap(x0, x1);
    y0 -= q * y1;
    swap(y0, y1);
  }
  x = x0;
  y = y0;
  return a;
}
static inline int ctz(unsigned x) { return __builtin_ctz(x); }
static inline int ctzll(unsigned long long x) { return __builtin_ctzll(x); }
static inline int clz(unsigned x) { return __builtin_clz(x); }
static inline int clzll(unsigned long long x) { return __builtin_clzll(x); }
static inline int popcnt(unsigned x) { return __builtin_popcount(x); }
static inline int popcntll(unsigned long long x) {
  return __builtin_popcountll(x);
}
static inline int bsr(unsigned x) { return 31 ^ clz(x); }
static inline int bsrll(unsigned long long x) { return 63 ^ clzll(x); }
static multiset<int> car[100016], cde[100016];
static vector<pair<int, int> > arr[1000016], dep[1000016];
int n, m, k, tmx = 0;
int in = 0, out = 0;
long long cost = 0, ans = 1e18;
bool ok = false;
void add_arr(int i, int c) {
  if (car[i].empty())
    ++in;
  else
    cost -= *car[i].begin();
  car[i].insert(c);
  cost += *car[i].begin();
}
void rem_dep(int i, int c) {
  assert(!cde[i].empty());
  cost -= *cde[i].begin();
  cde[i].erase(cde[i].find(c));
  if (cde[i].empty())
    --out;
  else
    cost += *cde[i].begin();
}
int main() {
  canhazfast();
  cin >> n >> m >> k;
  for (int i = 0; i < m; ++i) {
    int d, f, t, c;
    cin >> d >> f >> t >> c;
    tmx = max(tmx, d);
    if (t == 0)
      arr[d].emplace_back(f, c);
    else
      dep[d].emplace_back(t, c);
  }
  for (int t = tmx; t > k; --t) {
    for (const pair<int, int> &p : dep[t]) {
      int i = p.first, c = p.second;
      if (cde[i].empty())
        ++out;
      else
        cost -= *cde[i].begin();
      cde[i].insert(c);
      cost += *cde[i].begin();
    }
  }
  for (int t = 1; t + k <= tmx; ++t) {
    if (in == n && out == n) {
      ok = true, ans = min(ans, cost);
    }
    for (pair<int, int> p : arr[t]) add_arr(p.first, p.second);
    for (pair<int, int> p : dep[t + k]) rem_dep(p.first, p.second);
  }
  cout << (ok ? ans : -1LL);
  return 0;
}
