#include <bits/stdc++.h>
using namespace std;
bool debug = 0;
int n, m, k;
int dx[4] = {0, 1, 0, -1}, dy[4] = {1, 0, -1, 0};
string direc = "RDLU";
long long ln, lk, lm;
void etp(bool f = 0) {
  puts(f ? "YES" : "NO");
  exit(0);
}
void addmod(int &x, int y, int mod = 1000000007) {
  assert(y >= 0);
  x += y;
  if (x >= mod) x -= mod;
  assert(x >= 0 && x < mod);
}
void et() {
  puts("-1");
  exit(0);
}
long long fastPow(long long x, long long y, int mod = 1000000007) {
  long long ans = 1;
  while (y > 0) {
    if (y & 1) ans = (x * ans) % mod;
    x = x * x % mod;
    y >>= 1;
  }
  return ans;
}
int d[1000005], f[1000005], t[1000005], c[1000005], D;
vector<int> in[1000005], ot[1000005];
long long bf[1000005], af[1000005];
long long ans = 0;
int cnt, cc[1000005];
void fmain(int tid) {
  scanf("%d%d%d", &n, &m, &k);
  for (int(i) = 1; (i) <= (int)(m); (i)++) {
    scanf("%d%d%d%d", d + i, f + i, t + i, c + i);
    if (t[i] == 0) {
      in[d[i]].push_back(i);
    } else {
      ot[d[i]].push_back(i);
    }
    D = max(D, d[i]);
  }
  for (int(i) = 1; (i) <= (int)(n); (i)++) cc[i] = (1 << 30);
  for (int(i) = 1; (i) <= (int)(D); (i)++) {
    for (int id : in[i]) {
      int w = f[id];
      if (cc[w] == (1 << 30)) {
        cnt++;
        cc[w] = c[id];
        ans += c[id];
      } else if (cc[w] > c[id]) {
        ans -= cc[w];
        cc[w] = c[id];
        ans += c[id];
      }
    }
    if (cnt == n)
      bf[i] = ans;
    else
      bf[i] = (1LL << 60);
  }
  cnt = 0;
  for (int(i) = 1; (i) <= (int)(n); (i)++) cc[i] = (1 << 30);
  ans = 0;
  for (int i = D; i; i--) {
    for (int id : ot[i]) {
      int w = t[id];
      if (cc[w] == (1 << 30)) {
        cnt++;
        cc[w] = c[id];
        ans += cc[w];
      } else if (cc[w] > c[id]) {
        ans -= cc[w];
        cc[w] = c[id];
        ans += cc[w];
      }
    }
    if (cnt == n)
      af[i] = ans;
    else
      af[i] = (1LL << 60);
  }
  long long tans = (1LL << 60);
  for (int i = 2; i + k <= D; i++) {
    if (bf[i - 1] < (1LL << 60) && af[i + k] < (1LL << 60)) {
      tans = min(tans, bf[i - 1] + af[i + k]);
    }
  }
  if (tans == (1LL << 60)) tans = -1;
  printf("%lld\n", tans);
}
int main() {
  int t = 1;
  for (int(i) = 1; (i) <= (int)(t); (i)++) {
    fmain(i);
  }
  return 0;
}
