#include <bits/stdc++.h>
using namespace std;
const int maxn = 1e6 + 10;
const long long oo = 1e12;
const double eps = 1e-9;
int main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  long long n, m, k;
  cin >> n >> m >> k;
  vector<vector<pair<long long, long long>>> A(
      n, vector<pair<long long, long long>>());
  vector<vector<pair<long long, long long>>> B(
      n, vector<pair<long long, long long>>());
  for (int i = 0; i < m; ++i) {
    long long d, f, t, c;
    cin >> d >> f >> t >> c;
    if (f == 0)
      B[t - 1].push_back({-d, c});
    else
      A[f - 1].push_back({d, c});
  }
  for (int i = 0; i < n; ++i) {
    sort(A[i].begin(), A[i].end());
    sort(B[i].begin(), B[i].end());
  }
  long long mn = 0;
  long long mx = maxn;
  for (int i = 0; i < n; ++i) {
    if (B[i].empty() || A[i].empty()) {
      cout << -1 << endl;
      return 0;
    }
    mn = max(mn, A[i][0].first);
    mx = min(mx, -B[i][0].first);
  }
  vector<long long> V(n);
  vector<long long> dp1(maxn);
  vector<long long> dp2(maxn);
  for (int i = 0; i < n; ++i) {
    long long cur = oo;
    int lastd = -1;
    for (auto x : A[i]) {
      int d = x.first;
      long long c = x.second;
      if (lastd == d) continue;
      if (c < cur) {
        dp1[d] += c;
        if (cur != oo) dp1[d] -= cur;
        cur = c;
        lastd = d;
      }
    }
  }
  for (int i = 0; i < n; ++i) {
    long long cur = oo;
    int lastd = -1;
    for (auto x : B[i]) {
      int d = -x.first;
      long long c = x.second;
      if (lastd == d) continue;
      if (c < cur) {
        dp2[d] += c;
        if (cur != oo) dp2[d] -= cur;
        cur = c;
        lastd = d;
      }
    }
  }
  for (int i = 1; i < maxn; ++i) dp1[i] += dp1[i - 1];
  for (int i = maxn - 2; i >= 0; --i) dp2[i] += dp2[i + 1];
  long long ans = oo;
  for (int i = mn; i + k + 1 < maxn && i + k + 1 <= mx; ++i) {
    ans = min(ans, dp1[i] + dp2[i + k + 1]);
  }
  if (ans >= oo) ans = -1;
  cout << ans << endl;
  return 0;
}
