#include <bits/stdc++.h>
using namespace std;
const int maxn = 100010;
const int maxm = 1000010;
struct fli {
  int d, x, c;
  bool operator<(const fli &b) const { return d < b.d; }
} f1[maxn], f2[maxn];
int mi1[maxn], mi2[maxn];
long long d1[maxm], d2[maxm];
int main() {
  int n, m, k;
  scanf("%d%d%d", &n, &m, &k);
  int tot1 = 0, tot2 = 0;
  for (int j = 1; j <= m; ++j) {
    int d, f, t, c;
    scanf("%d%d%d%d", &d, &f, &t, &c);
    if (0 == f) {
      ++tot2;
      f2[tot2].d = d;
      f2[tot2].x = t;
      f2[tot2].c = c;
    } else {
      ++tot1;
      f1[tot1].d = d;
      f1[tot1].x = f;
      f1[tot1].c = c;
    }
  }
  sort(f1 + 1, f1 + tot1 + 1);
  sort(f2 + 1, f2 + tot2 + 1);
  reverse(f2 + 1, f2 + tot2 + 1);
  int last = 0;
  int oks = 0;
  long long sum = 0;
  for (int j = 1; j <= tot1; ++j) {
    if (0 == mi1[f1[j].x]) {
      sum += f1[j].c;
      mi1[f1[j].x] = f1[j].c;
      ++oks;
      if (oks == n) {
        last = f1[j].d;
        d1[last] = sum;
      }
    } else if (mi1[f1[j].x] > f1[j].c) {
      sum += f1[j].c - mi1[f1[j].x];
      mi1[f1[j].x] = f1[j].c;
    }
    if (oks == n) {
      while (last < f1[j].d) {
        ++last;
        d1[last] = d1[last - 1];
      }
      d1[last] = sum;
    }
  }
  if (oks == n) {
    for (; last < 1e6; ++last) d1[last] = sum;
  }
  oks = 0;
  last = n + 1;
  sum = 0;
  for (int j = 1; j <= tot2; ++j) {
    if (0 == mi2[f2[j].x]) {
      sum += f2[j].c;
      mi2[f2[j].x] = f2[j].c;
      ++oks;
      if (oks == n) {
        last = f2[j].d;
        d2[last] = sum;
      }
    } else if (mi2[f2[j].x] > f2[j].c) {
      sum += f2[j].c - mi2[f2[j].x];
      mi2[f2[j].x] = f2[j].c;
    }
    if (oks == n) {
      while (last > f2[j].d) {
        --last;
        d2[last] = d2[last + 1];
      }
      d2[last] = sum;
    }
  }
  if (oks == n) {
    for (; last > 0; --last) d2[last] = sum;
  }
  long long ans = 1e18;
  for (int j = k + 1; j <= 1e6; ++j) {
    int nx = j - k - 1;
    if (d1[nx] == 0 || d2[j] == 0) continue;
    ans = min(ans, d1[nx] + d2[j]);
  }
  if (1e18 == ans) ans = -1;
  printf("%lld\n", ans);
  return 0;
}
