#include <bits/stdc++.h>
using namespace std;
template <typename T>
inline bool chkmin(T &a, const T &b) {
  return a > b ? a = b, 1 : 0;
}
template <typename T>
inline bool chkmax(T &a, const T &b) {
  return a < b ? a = b, 1 : 0;
}
inline int read() {
  register int c = getchar(), sum(0), fg(1);
  while (c < '0' || c > '9') {
    if (c == '-') fg = -1;
    c = getchar();
  }
  while (c >= '0' && c <= '9') sum = sum * 10 + c - '0', c = getchar();
  return sum * fg;
}
const int oo = 0x3f3f3f3f;
const int maxn = 100000;
struct flight {
  long long d, first, w;
  inline bool operator<(const flight &adj) const { return d < adj.d; }
} a[maxn + 5], b[maxn + 5];
int L1 = 0, L2 = 0;
int N, M, k;
long long prefix[maxn + 5], suffix[maxn + 5], Min[maxn + 5];
int main() {
  N = read(), M = read(), k = read();
  for (int i = (1), i_end_ = (M); i <= i_end_; ++i) {
    int d, first, second, w;
    d = read(), first = read(), second = read(), w = read();
    if (second == 0) a[++L1].d = d, a[L1].first = first, a[L1].w = w;
    if (first == 0) b[++L2].d = d, b[L2].first = second, b[L2].w = w;
  }
  sort(a + 1, a + L1 + 1);
  sort(b + 1, b + L2 + 1);
  long long sum = 0, cnt = 0;
  memset(Min, 0, sizeof Min);
  for (int i = (1), i_end_ = (L1); i <= i_end_; ++i) {
    sum -= Min[a[i].first];
    if (!Min[a[i].first])
      ++cnt, Min[a[i].first] = a[i].w;
    else
      chkmin(Min[a[i].first], a[i].w);
    sum += Min[a[i].first];
    prefix[i] = cnt == N ? sum : LLONG_MAX;
  }
  sum = cnt = 0, memset(Min, 0, sizeof Min);
  for (int i = L2; i; --i) {
    sum -= Min[b[i].first];
    if (!Min[b[i].first])
      ++cnt, Min[b[i].first] = b[i].w;
    else
      chkmin(Min[b[i].first], b[i].w);
    sum += Min[b[i].first];
    suffix[i] = cnt == N ? sum : LLONG_MAX;
  }
  int r = 0;
  long long ans = LLONG_MAX;
  for (int l = (1), l_end_ = (L1); l <= l_end_; ++l) {
    while (r <= L2 && a[l].d + k >= b[r].d) ++r;
    if (r > L2) break;
    if (prefix[l] < LLONG_MAX && suffix[r] < LLONG_MAX)
      chkmin(ans, prefix[l] + suffix[r]);
  }
  printf("%lld\n", ans >= LLONG_MAX ? -1 : ans);
  return 0;
}
