#include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 5;
const int M = 1e6 + 5;
const long long INF = 1e15;
struct Flight {
  int d, f, t, c;
  friend bool operator<(const Flight& a, const Flight& b) { return a.d < b.d; }
};
static int n, m, k;
Flight flt[N];
int Min[N];
long long L[M], R[M];
int update(int i, int c, long long& cost) {
  if (Min[i] == -1) {
    Min[i] = c;
    cost += c;
    return 1;
  }
  if (c < Min[i]) {
    cost += c - Min[i];
    Min[i] = c;
  }
  return 0;
}
int main() {
  while (scanf("%d%d%d", &n, &m, &k) != EOF) {
    for (int i = 0; i < m; i++)
      scanf("%d%d%d%d", &flt[i].d, &flt[i].f, &flt[i].t, &flt[i].c);
    sort(flt, flt + m);
    for (int i = 0; i < M; i++) L[i] = R[i] = INF;
    int cnt = 0;
    long long cost = 0;
    memset(Min, -1, sizeof(Min));
    for (int i = 0; i < m; i++)
      if (flt[i].f != 0) {
        cnt += update(flt[i].f, flt[i].c, cost);
        if (cnt == n) L[flt[i].d] = cost;
      }
    for (int i = 1; i < M; i++) L[i] = min(L[i - 1], L[i]);
    cost = cnt = 0;
    memset(Min, -1, sizeof(Min));
    for (int i = m - 1; i >= 0; i--)
      if (flt[i].t != 0) {
        cnt += update(flt[i].t, flt[i].c, cost);
        if (cnt == n) R[flt[i].d] = cost;
      }
    for (int i = M - 2; i >= 0; i--) R[i] = min(R[i + 1], R[i]);
    cost = INF;
    for (int i = 0; i + k + 1 < M; i++) cost = min(cost, L[i] + R[i + k + 1]);
    if (cost == INF)
      puts("-1");
    else
      printf("%lld\n", cost);
  }
  return 0;
}
