#include <bits/stdc++.h>
using namespace std;
int dx[] = {0, 0, 1, -1};
int dy[] = {1, -1, 0, 0};
int dx8[] = {0, 0, 1, 1, 1, -1, -1, -1};
int dy8[] = {1, -1, -1, 0, 1, -1, 0, 1};
int kx8[] = {1, 1, 2, 2, -1, -1, -2, -2};
int ky8[] = {2, -2, 1, -1, 2, -2, 1, -1};
long long bigmod(long long a, long long b, long long c) {
  if (b == 0) return 1 % c;
  long long x = bigmod(a, b / 2, c);
  x = (x * x) % c;
  if (b % 2 == 1) x = (x * a) % c;
  return x;
}
long long poww(long long a, long long b) {
  if (b == 0) return 1;
  long long x = poww(a, b / 2);
  x = x * x;
  if (b % 2 == 1) x = (x * a);
  return x;
}
long long mod_inverse(long long a, long long mod) {
  return bigmod(a, mod - 2, mod);
}
const int M = 1e6 + 5;
vector<pair<long long, long long> > come[M], go[M];
long long bward[M], fward[M], sum[M];
int main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  long long n, m, k;
  cin >> n >> m >> k;
  for (int i = 0; i < (m); i++) {
    int d, f, t, c;
    cin >> d >> f >> t >> c;
    if (t == 0)
      come[d].push_back({f, c});
    else
      go[d].push_back({t, c});
  }
  long long ltot = 0, rtot = 0;
  for (int i = 1; i <= n; i++) {
    bward[i] = fward[i] = 1e13;
    ltot += fward[i];
  }
  rtot = ltot;
  for (int i = 1e6; i >= 1; i--) {
    for (auto x : go[i]) {
      int u = x.first;
      long long c = x.second;
      if (bward[u] > c) {
        rtot -= bward[u];
        bward[u] = c;
        rtot += c;
      }
    }
    sum[i] = rtot;
  }
  long long res = 1e18;
  for (int i = 1; i <= 1e6; i++) {
    for (auto x : come[i]) {
      int u = x.first;
      long long c = x.second;
      if (fward[u] > c) {
        ltot -= fward[u];
        fward[u] = c;
        ltot += c;
      }
    }
    if (i + k + 1 <= 1e6) res = min(res, ltot + sum[i + k + 1]);
  }
  if (res >= 1e13) res = -1;
  cout << res << endl;
  return 0;
}
