#include <bits/stdc++.h>
using namespace std;
const int MAXN = 100005;
const int MAXD = 1000005;
const long long INF = 0x3f3f3f3f3f3f3f3f;
int n, m, k, md;
long long ans = INF;
long long qz[MAXD], MIN[MAXN];
long long zr[MAXD];
struct edge {
  int t, u, v, p;
  bool operator<(const edge &px) const { return t < px.t; }
} e[MAXN];
long long Read() {
  long long x = 0, f = 1;
  char c = getchar();
  while (c > '9' || c < '0') {
    if (c == '-') f = -1;
    c = getchar();
  }
  while (c >= '0' && c <= '9') {
    x = (x * 10) + (c ^ 48);
    c = getchar();
  }
  return x * f;
}
void Put1(long long x) {
  if (x > 9) Put1(x / 10);
  putchar(x % 10 ^ 48);
}
void Put(long long x, char c = -1) {
  if (x < 0) putchar('-'), x = -x;
  Put1(x);
  if (c >= 0) putchar(c);
}
template <typename T>
T Max(T x, T y) {
  return x > y ? x : y;
}
template <typename T>
T Min(T x, T y) {
  return x < y ? x : y;
}
template <typename T>
T Abs(T x) {
  return x < 0 ? -x : x;
}
int main() {
  n = Read();
  m = Read();
  k = Read();
  for (int i = 1; i <= m; ++i) {
    e[i].t = Read();
    e[i].u = Read();
    e[i].v = Read();
    e[i].p = Read();
    md = Max(e[i].t, md);
  }
  sort(e + 1, e + m + 1);
  for (int i = 1; i <= n; ++i) MIN[i] = INF;
  for (int i = 1; i <= md; ++i) zr[i] = qz[i] = INF;
  int zai = 0;
  long long tot = 0;
  for (int i = 1, j = 1; i <= md && j <= m; ++i) {
    while (e[j].u == 0 && j <= m) j++;
    if (e[j].t > i) continue;
    if (j > m) break;
    if (e[j].p < MIN[e[j].u]) {
      if (MIN[e[j].u] != INF)
        tot -= MIN[e[j].u];
      else
        zai++;
      tot += e[j].p;
      MIN[e[j].u] = e[j].p;
      if (zai == n) qz[i] = tot;
    }
    i--;
    j++;
  }
  for (int i = 2; i <= md; ++i) qz[i] = Min(qz[i - 1], qz[i]);
  for (int i = 1; i <= n; ++i) MIN[i] = INF;
  tot = zai = 0;
  for (int i = md, j = m; i >= 1 && j >= 1; --i) {
    while (e[j].v == 0 && j >= 1) j--;
    if (e[j].t < i) continue;
    if (j <= 0) break;
    if (e[j].p < MIN[e[j].v]) {
      if (MIN[e[j].v] != INF)
        tot -= MIN[e[j].v];
      else
        zai++;
      tot += e[j].p;
      MIN[e[j].v] = e[j].p;
      if (zai == n) zr[i] = tot;
    }
    i++;
    j--;
  }
  for (int i = md - 1; i >= 1; --i) zr[i] = Min(zr[i + 1], zr[i]);
  for (int i = 2; i <= md - k; ++i) ans = Min(ans, qz[i - 1] + zr[i + k]);
  if (ans == INF)
    printf("-1");
  else
    Put(ans);
  return 0;
}
