#include <bits/stdc++.h>
using namespace std;
template <typename T, typename U>
inline void chkmax(T& x, U y) {
  if (x < y) x = y;
}
template <typename T, typename U>
inline void chkmin(T& x, U y) {
  if (y < x) x = y;
}
const long long INF = 1LL << 40;
const int MAXN = 110000;
const int MAXM = 1100000;
vector<pair<int, int> > A[MAXM], B[MAXM];
long long dp[MAXN], f[MAXM];
void solve(int n) {
  long long sum = 0;
  for (int i = 1; i <= n; i++) dp[i] = INF, sum += dp[i];
  for (int d = 1000000; d > 0; d--) {
    for (int j = 0; j < ((int)(B[d].size())); j++) {
      int i = B[d][j].first, c = B[d][j].second;
      if (dp[i] > c) sum += c - dp[i], dp[i] = c;
    }
    f[d] = sum;
  }
}
int main() {
  int n, m, k;
  scanf("%d%d%d", &n, &m, &k);
  for (int i = 0; i < m; i++) {
    int d, f, t, c;
    scanf("%d%d%d%d", &d, &f, &t, &c);
    if (!t)
      A[d].push_back(pair<int, int>(f, c));
    else
      B[d].push_back(pair<int, int>(t, c));
  }
  solve(n);
  long long sum = 0;
  for (int i = 1; i <= n; i++) dp[i] = INF, sum += dp[i];
  long long ans = 1LL << 60;
  for (int d = 1; d + k + 1 <= 1000000; d++) {
    for (int j = 0; j < ((int)(A[d].size())); j++) {
      int i = A[d][j].first, c = A[d][j].second;
      if (dp[i] > c) sum += c - dp[i], dp[i] = c;
    }
    chkmin(ans, sum + f[d + k + 1]);
  }
  if (ans > (1LL << 40)) ans = -1;
  cout << ans << endl;
  return 0;
}
