#include <bits/stdc++.h>
using namespace std;
const int MOD = 1e9 + 7;
const int N = 1e5, M = 1e6;
const double EPS = 1e-9;
const int INF = 1e9;
const long long INFL = 1000000000000000LL;
int n, m, k;
int minCostFirst[N + 5];
int minCostLast[N + 5];
long long prefCost[N + 5];
long long suffCost[N + 5];
struct trip {
  int d, f, t, c;
} ar[N + 5];
bool CF(const trip &a, const trip &b) {
  if (a.d != b.d) return a.d < b.d;
  if (a.t != b.t) return a.t < b.t;
  if (a.f != b.f) return a.f < b.f;
  return a.c < b.c;
}
int precomfirst() {
  int sisa = n;
  int idx = -1;
  long long pref = 0;
  for (int i = 0; i < m; ++i) {
    if (ar[i].t == 0) {
      if (minCostFirst[ar[i].f] == -1) {
        minCostFirst[ar[i].f] = ar[i].c;
        pref += ar[i].c;
        sisa--;
      } else {
        if (ar[i].c < minCostFirst[ar[i].f]) {
          pref += ar[i].c - minCostFirst[ar[i].f];
          minCostFirst[ar[i].f] = ar[i].c;
        }
      }
    }
    if (sisa == 0 && idx == -1) {
      idx = i;
    }
    prefCost[i] = pref;
  }
  return idx;
}
int precomlast() {
  int sisa = n;
  int idx = -1;
  long long suff = 0;
  for (int i = m - 1; i >= 0; --i) {
    if (ar[i].f == 0) {
      if (minCostLast[ar[i].t] == -1) {
        minCostLast[ar[i].t] = ar[i].c;
        suff += ar[i].c;
        sisa--;
      } else {
        if (ar[i].c < minCostLast[ar[i].t]) {
          suff += ar[i].c - minCostLast[ar[i].t];
          minCostLast[ar[i].t] = ar[i].c;
        }
      }
    }
    if (sisa == 0 && idx == -1) {
      idx = i;
    }
    suffCost[i] = suff;
  }
  return idx;
}
int search(int day) {
  int l = 0;
  int r = m - 1;
  int ans = m;
  while (l <= r) {
    int piv = (l + r) >> 1;
    if (ar[piv].d >= day) {
      ans = piv;
      r = piv - 1;
    } else {
      l = piv + 1;
    }
  }
  return ans;
}
long long mintot = 0;
int main() {
  scanf("%d%d%d", &n, &m, &k);
  memset(minCostFirst, -1, sizeof minCostFirst);
  memset(minCostLast, -1, sizeof minCostLast);
  for (int i = 0; i < m; ++i)
    scanf("%d%d%d%d", &ar[i].d, &ar[i].f, &ar[i].t, &ar[i].c);
  sort(ar, ar + m, CF);
  int minfirst = precomfirst();
  int maxlast = precomlast();
  if (minfirst == -1 || maxlast == -1 ||
      ar[minfirst].d + k + 1 > ar[maxlast].d) {
    puts("-1");
    return 0;
  }
  long long minall = INFL;
  for (int i = minfirst; i <= maxlast; ++i) {
    int minidx = search(ar[i].d + k + 1);
    if (minidx <= maxlast) {
      minall = min(minall, prefCost[i] + suffCost[minidx]);
    }
  }
  printf("%lld\n", minall);
  return 0;
}
