#include <bits/stdc++.h>
using namespace std;
const long long MAXX = 1e6 + 5;
long long n, m, k;
struct ask {
  long long x;
  long long st;
};
vector<ask> v1[MAXX], v2[MAXX];
long long in[MAXX], out[MAXX];
long long taken1[MAXX], taken2[MAXX];
const long long INF = 1e17;
void read() {
  long long i, j;
  ask aa;
  long long a1, a2, a3, a4;
  cin >> n >> m >> k;
  for (i = 0; i < m; i++) {
    cin >> a1 >> a2 >> a3 >> a4;
    if (a3 == 0) {
      aa.x = a2;
      aa.st = a4;
      v1[a1].push_back(aa);
    } else {
      aa.x = a3;
      aa.st = a4;
      v2[a1].push_back(aa);
    }
  }
}
void solve() {
  long long i, j, sum = 0;
  long long cnt = 0, sz;
  ask aa;
  for (i = 0; i < MAXX; i++) {
    in[i] = out[i] = INF;
  }
  for (i = 1; i < MAXX; i++) {
    sz = v1[i].size();
    if (!sz) {
      in[i] = in[i - 1];
      continue;
    }
    for (j = 0; j < sz; j++) {
      aa = v1[i][j];
      if (!taken1[aa.x]) {
        cnt++;
        sum += aa.st;
        taken1[aa.x] = aa.st;
      } else {
        sum -= taken1[aa.x];
        taken1[aa.x] = min(taken1[aa.x], aa.st);
        sum += taken1[aa.x];
      }
      if (cnt == n) {
        in[i] = sum;
      } else
        in[i] = INF;
    }
  }
  cnt = 0;
  sum = 0;
  for (i = MAXX - 2; i >= 1; i--) {
    sz = v2[i].size();
    if (!sz) {
      out[i] = out[i + 1];
      continue;
    }
    for (j = 0; j < sz; j++) {
      aa = v2[i][j];
      if (!taken2[aa.x]) {
        cnt++;
        sum += aa.st;
        taken2[aa.x] = aa.st;
      } else {
        sum -= taken2[aa.x];
        taken2[aa.x] = min(taken2[aa.x], aa.st);
        sum += taken2[aa.x];
      }
      if (cnt == n) {
        out[i] = sum;
      } else
        out[i] = INF;
    }
  }
}
int main() {
  read();
  solve();
  long long i;
  long long ans = INF;
  long long nz;
  for (i = 1; i < MAXX - k; i++) {
    if (in[i - 1] == INF || out[i + k] == INF) {
      continue;
    }
    nz = in[i - 1] + out[i + k];
    ans = min(ans, nz);
  }
  if (ans == INF) ans = -1;
  cout << ans << endl;
  return 0;
}
