#include <bits/stdc++.h>
using namespace std;
template <class T>
inline bool getmin(T *a, const T &b) {
  if (b < *a) {
    *a = b;
    return true;
  }
  return false;
}
template <class T>
inline bool getmax(T *a, const T &b) {
  if (b > *a) {
    *a = b;
    return true;
  }
  return false;
}
template <class T>
inline void read(T *a) {
  char c;
  while (isspace(c = getchar())) {
  }
  bool flag = 0;
  if (c == '-')
    flag = 1, *a = 0;
  else
    *a = c - 48;
  while (isdigit(c = getchar())) *a = *a * 10 + c - 48;
  if (flag) *a = -*a;
}
const int mo = 40009;
template <class T>
T pow(T a, T b, int c = mo) {
  T res = 1;
  for (T i = 1; i <= b; i <<= 1, a = 1LL * a * a % c)
    if (b & i) res = 1LL * res * a % c;
  return res;
}
const int N = 1000010;
struct node {
  int d, f, t, c;
} a[N];
int n, k, m;
long long f[N], g[N];
int mx[N];
int num;
bool cmp(node A, node B) { return A.d < B.d; }
int ll, rr;
int main() {
  int tot = 0;
  cin >> n >> m >> k;
  for (register int i = (1); i <= (m); ++i) {
    read(&a[i].d), read(&a[i].f), read(&a[i].t), read(&a[i].c);
    getmax(&tot, a[i].d);
  }
  sort(a + 1, a + m + 1, cmp);
  for (register int i = (1); i <= (n); ++i) mx[i] = 1e9;
  for (register int i = (1); i <= (n); ++i) f[0] += mx[i];
  int j = 1;
  num = n;
  ll = 0, rr = 0;
  for (register int i = (1); i <= (tot); ++i) {
    f[i] = f[i - 1];
    while (j <= m && a[j].d == i) {
      if (!a[j].t && mx[a[j].f] > a[j].c) {
        if (mx[a[j].f] == 1e9) --num;
        f[i] -= mx[a[j].f], mx[a[j].f] = a[j].c, f[i] += mx[a[j].f];
      }
      ++j;
    }
    if (!num && !ll) ll = i;
  }
  num = n;
  for (register int i = (1); i <= (n); ++i) mx[i] = 1e9;
  for (register int i = (1); i <= (n); ++i) g[tot + 1] += mx[i];
  j = m;
  for (int i = (tot); i >= (1); --i) {
    g[i] = g[i + 1];
    while (j >= 1 && a[j].d == i) {
      if (!a[j].f && mx[a[j].t] > a[j].c) {
        if (mx[a[j].t] == 1e9) --num;
        g[i] -= mx[a[j].t], mx[a[j].t] = a[j].c, g[i] += mx[a[j].t];
      }
      --j;
    }
    if (!num && !rr) rr = i;
  }
  long long ans = -1;
  if (ll && rr) {
    for (register int i = (ll); i <= (tot); ++i) {
      if (i + k + 1 > rr) break;
      if (ans == -1 || ans > f[i] + g[i + k + 1]) ans = f[i] + g[i + k + 1];
    }
  }
  cout << ans << endl;
}
