#include <bits/stdc++.h>
using namespace std;
const int mod = 1e9 + 7;
const int maxn = 200005;
const int inf = 1e9 + 5;
int mini[maxn], arrday[maxn];
set<pair<int, int>> departure[maxn];
void solve() {
  int n, m, k;
  cin >> n >> m >> k;
  for (int i = 1; i <= n; i++) mini[i] = inf;
  vector<pair<int, pair<int, int>>> arrival;
  for (int i = 1; i <= m; i++) {
    int d, f, t, c;
    cin >> d >> f >> t >> c;
    if (f == 0) {
      departure[t].insert(pair<int, int>(c, d));
    } else {
      arrival.push_back(pair<int, pair<int, int>>(d, pair<int, int>(f, c)));
    }
  }
  sort(arrival.begin(), arrival.end());
  long long int ans = 1e18;
  int sin = n;
  int idx = 0;
  int sz = arrival.size();
  while (idx < sz && sin) {
    int ciudad = arrival[idx].second.first;
    int past = mini[ciudad];
    if (past == inf) {
      mini[ciudad] = arrival[idx].second.second;
      sin--;
    } else {
      mini[ciudad] = min(mini[ciudad], arrival[idx].second.second);
    }
    idx++;
  }
  if (sin) {
    cout << -1 << '\n';
    return;
  }
  long long int costo = 0ll;
  for (int i = 1; i <= n; i++) {
    costo += mini[i];
  }
  idx--;
  while (idx < sz) {
    int dia = arrival[idx].first;
    while (idx < sz && arrival[idx].first == dia) {
      int c = arrival[idx].second.first;
      if (arrival[idx].second.second < mini[c]) {
        costo -= mini[c];
        mini[c] = min(mini[c], arrival[idx].second.second);
        costo += mini[c];
      }
      idx++;
    }
    int vamos = dia + k;
    int sal = 0;
    long long int aux = 0ll;
    for (int i = 1; i <= n; i++) {
      while (!departure[i].empty() && (*departure[i].begin()).second <= vamos) {
        departure[i].erase(departure[i].begin());
      }
      if (departure[i].empty()) {
        sal = 1;
        break;
      }
      aux += (*departure[i].begin()).first;
      costo += (*departure[i].begin()).first;
    }
    if (sal) break;
    ans = min(ans, costo);
    costo -= aux;
  }
  if (ans == 1e18) ans = -1;
  cout << ans << '\n';
}
int main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  int t = 1;
  while (t--) {
    solve();
  }
  return 0;
}
