#include <bits/stdc++.h>
using namespace std;
using namespace std;
const long long nDays = 1000005;
int main() {
  cin.sync_with_stdio(0);
  long long n, m, k;
  cin >> n >> m >> k;
  vector<vector<pair<long long, long long> > > from(nDays);
  vector<vector<pair<long long, long long> > > to(nDays);
  for (long long i = 0; i < (m); i++) {
    long long d, f, t, c;
    cin >> d >> f >> t >> c;
    if (f == 0) {
      from[d - 1].push_back(pair<long long, long long>({t - 1, c}));
    } else {
      to[d - 1].push_back(pair<long long, long long>({f - 1, c}));
    }
  }
  vector<long long> prefs(nDays);
  {
    vector<long long> costs(n, 9999999999999ll);
    long long currSum = n * 9999999999999ll;
    for (long long i = 0; i < (nDays); i++) {
      for (long long j = 0; j < (((long long)(to[i]).size())); j++) {
        currSum -= costs[to[i][j].first];
        costs[to[i][j].first] = min(to[i][j].second, costs[to[i][j].first]);
        currSum += costs[to[i][j].first];
      }
      prefs[i] = currSum;
    }
  }
  vector<long long> suffs(nDays);
  {
    vector<long long> costs(n, 9999999999999ll);
    long long currSum = n * 9999999999999ll;
    for (long long i = (nDays - 1); i >= (0); i--) {
      for (long long j = 0; j < (((long long)(from[i]).size())); j++) {
        currSum -= costs[from[i][j].first];
        costs[from[i][j].first] =
            min(from[i][j].second, costs[from[i][j].first]);
        currSum += costs[from[i][j].first];
      }
      suffs[i] = currSum;
    }
  }
  long long minPrice = 9999999999999ll;
  for (long long i = 0; i < (nDays); i++) {
    if (i + k + 1 >= nDays) continue;
    minPrice = min(minPrice, prefs[i] + suffs[i + k + 1]);
  }
  if (minPrice == 9999999999999ll)
    cout << "-1\n";
  else
    cout << minPrice << "\n";
  return 0;
}
