#include <bits/stdc++.h>
using namespace std;
const int N = 1000007;
const long long inf = 2000000000001;
struct flight {
  int d, f, t, c;
  bool operator<(flight f) const { return d < f.d; }
};
long long seg[200007];
int n, m, k, d, f, t, c;
void update(int p, long long v) {
  for (seg[p += n] = v; p > 1; p >>= 1) {
    seg[p >> 1] = seg[p] + seg[p ^ 1];
  }
}
long long query() {
  long long ans = 0;
  int l = 0, r = n;
  for (l += n, r += n; l < r; l >>= 1, r >>= 1) {
    if (l & 1) ans += seg[l++];
    if (r & 1) ans += seg[--r];
  }
  return ans;
}
long long pref[N], suff[N];
int main() {
  ios::sync_with_stdio(false);
  vector<flight> v;
  flight fl;
  cin >> n >> m >> k;
  for (int i = 0; i < m; ++i) {
    cin >> d >> f >> t >> c;
    fl = {d, f, t, c};
    v.push_back(fl);
  }
  sort(v.begin(), v.end());
  for (int i = 0; i < n; ++i) update(i, inf);
  int p = 0;
  for (int i = 1; i <= N; ++i) {
    while (p < v.size() and i >= v[p].d) {
      if (v[p].f and seg[v[p].f - 1 + n] > v[p].c) update(v[p].f - 1, v[p].c);
      p++;
    }
    pref[i] = query();
  }
  for (int i = 0; i < n; ++i) update(i, inf);
  p = v.size() - 1;
  for (int i = N; i > 0; --i) {
    while (p >= 0 and i <= v[p].d) {
      if (v[p].t and seg[v[p].t - 1 + n] > v[p].c) update(v[p].t - 1, v[p].c);
      p--;
    }
    suff[i] = query();
  }
  long long ans = inf;
  for (int i = 2; i <= N - k; ++i) {
    ans = min(ans, pref[i - 1] + suff[i + k]);
  }
  if (ans >= inf)
    cout << -1 << endl;
  else
    cout << ans << endl;
}
