#include <bits/stdc++.h>
using namespace std;
int OO = 1000000000;
int a[100005], l[100005], f[100005], t[100005], c[100005], ta[1000005];
long long dp[1000005];
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  int n, m, k, tl = 0, it = 0, te;
  cin >> n >> m >> k;
  vector<pair<int, int>> day;
  for (int i = 0; i < m; i++) {
    cin >> te >> f[i] >> t[i] >> c[i];
    day.push_back(make_pair(te, i));
  }
  sort(day.begin(), day.end());
  for (int i = 1; i <= 1000000; i++) {
    dp[i] = dp[i - 1];
    ta[i] = ta[i - 1];
    while (it < day.size() && day[it].first == i) {
      int d = day[it++].second;
      if (f[d] && (a[f[d]] == 0 || a[f[d]] > c[d])) {
        if (a[f[d]] == 0) {
          ta[i]++;
          dp[i] += c[d];
        } else {
          dp[i] += c[d] - a[f[d]];
        }
        a[f[d]] = c[d];
      }
    }
  }
  long long r = 0, ans = 10000000000000000;
  it = day.size() - 1;
  for (int i = 1000000; i >= k + 2; i--) {
    while (it >= 0 && day[it].first == i) {
      int d = day[it--].second;
      if (t[d] && (l[t[d]] == 0 || l[t[d]] > c[d])) {
        if (l[t[d]] == 0) {
          tl++;
          r += c[d];
        } else {
          r += c[d] - l[t[d]];
        }
        l[t[d]] = c[d];
      }
    }
    if (tl == n && ta[i - k - 1] == n) ans = min(ans, r + dp[i - k - 1]);
  }
  if (ans >= 10000000000000000)
    cout << -1;
  else
    cout << ans;
  return 0;
}
