#include <bits/stdc++.h>
using namespace std;
const long long int N = 1e6 + 5;
const long long int M = 1e5 + 5;
const long long int mod = 1e9 + 7;
const long long int m1 = 1e9 + 7;
const long long int m2 = 1e9 + 9;
const long long int p1 = 402653189;
const long long int p2 = 1610612741;
const int LN = 61;
long long int powermodm(long long int x, long long int n, long long int M) {
  long long int result = 1;
  while (n > 0) {
    if (n % 2 == 1) result = (result * x) % M;
    x = (x * x) % M;
    n = n / 2;
  }
  return result;
}
long long int power(long long int _a, long long int _b) {
  long long int _r = 1;
  while (_b) {
    if (_b % 2 == 1) _r = (_r * _a);
    _b /= 2;
    _a = (_a * _a);
  }
  return _r;
}
long long int gcd(long long int a, long long int b) {
  if (a == 0) return b;
  return gcd(b % a, a);
}
long long int lcm(long long int a, long long int b) {
  return (max(a, b) / gcd(a, b)) * min(a, b);
}
long long int dx[4] = {-1, 1, 0, 0};
long long int dy[4] = {0, 0, 1, -1};
long long int pw[LN], fact[N], invfact[N];
void pre() {
  fact[0] = 1;
  for (int i = 0; i < LN; i++) pw[i] = power(2, i);
  for (int i = 1; i < N; i++) fact[i] = (i * fact[i - 1]) % mod;
  for (int i = 0; i < N; i++) invfact[i] = powermodm(fact[i], mod - 2, mod);
}
long long int d[N], f[N], t[N], c[N];
long long int pref[N], suff[N];
vector<long long int> in[N], out[N];
long long int mi[N];
int main() {
  ios::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  ;
  long long int i, j;
  long long int n, m, k;
  cin >> n >> m >> k;
  for (i = 0; i < m; i++) {
    cin >> d[i] >> f[i] >> t[i] >> c[i];
    if (f[i] == 0)
      out[d[i]].push_back(i);
    else
      in[d[i]].push_back(i);
  }
  long long int currans = 0;
  for (i = 1; i <= n; i++) mi[i] = 1e12;
  currans = n * 1e12;
  for (i = 1; i < N; i++) {
    for (j = 0; j < in[i].size(); j++) {
      long long int idx = in[i][j];
      currans -= mi[f[idx]];
      mi[f[idx]] = min(mi[f[idx]], c[idx]);
      currans += mi[f[idx]];
    }
    pref[i] = currans;
  }
  for (i = 1; i <= n; i++) mi[i] = 1e12;
  currans = n * 1e12;
  for (i = N - 1; i >= 1; i--) {
    for (j = 0; j < out[i].size(); j++) {
      long long int idx = out[i][j];
      currans -= mi[t[idx]];
      mi[t[idx]] = min(mi[t[idx]], c[idx]);
      currans += mi[t[idx]];
    }
    suff[i] = currans;
  }
  long long int ans = 1e11 + 5;
  for (i = 2; i + k + 1 < N; i++) {
    ans = min(ans, pref[i - 1] + suff[i + k]);
  }
  if (ans == 1e11 + 5)
    cout << "-1";
  else
    cout << ans;
  return 0;
}
