#include <bits/stdc++.h>
using namespace std;
template <class T>
inline void upd1(T& a, T b) {
  a > b ? a = b : 0;
}
template <class T>
inline void upd2(T& a, T b) {
  a < b ? a = b : 0;
}
struct ano {
  operator long long() {
    long long x = 0, y = 0, c = getchar();
    while (c < 48) y = c == 45, c = getchar();
    while (c > 47) x = x * 10 + c - 48, c = getchar();
    return y ? -x : x;
  }
} buf;
const long long inf = 1e12;
const int N = 1e5 + 5;
vector<tuple<int, int, int>> a, b;
int n = buf, c[N];
long long f[N], g[N], t[N];
template <class T>
void sol(T a, T b, long long* c) {
  fill_n(t + 1, n, inf);
  long long s = n * inf;
  for (; a < b; ++a) {
    int u = get<1>(*a), w = get<2>(*a);
    if (w < t[u]) s -= t[u] - w, t[u] = w;
    *c++ = s;
  }
}
int main() {
  int m = buf, k = buf;
  while (m--) {
    int t = buf, u = buf, v = buf, w = buf;
    if (u)
      a.push_back(make_tuple(t, u, w));
    else
      b.push_back(make_tuple(t, v, w));
  }
  sort(a.begin(), a.end());
  sort(b.begin(), b.end());
  reverse(b.begin(), b.end());
  sol(a.begin(), a.end(), f);
  sol(b.begin(), b.end(), g);
  for (int i = 0; i < a.size(); ++i) c[i] = get<0>(a[i]);
  long long s = inf;
  for (int i = 0; i < b.size(); ++i) {
    int j = upper_bound(c, c + a.size(), get<0>(b[i]) - k - 1) - c - 1;
    if (~j) upd1(s, g[i] + f[j]);
  }
  printf(
      "%I64d"
      "\n",
      s < inf ? s : -1);
}
