#include <bits/stdc++.h>
using namespace std;
struct flight {
  int d, f, t, c;
  flight() {}
  flight(int d, int f, int t, int c) : d(d), f(f), t(t), c(c) {}
  bool operator<(const flight& a) const { return d > a.d; }
};
int n, m, k;
priority_queue<flight> arr, dep;
priority_queue<pair<int, int> > cheap[100010];
long long minarr[100010], arrcost, depcost;
int main() {
  cin >> n >> m >> k;
  for (int i = 0; i < m; i++) {
    int d, f, t, c;
    cin >> d >> f >> t >> c;
    if (t == 0) {
      arr.push(flight(d, f, t, c));
    } else {
      dep.push(flight(d, f, t, c));
      cheap[t].push(make_pair(-c, d));
    }
  }
  for (int i = 1; i <= n; i++) {
    if (cheap[i].empty()) {
      cout << -1 << '\n';
      return 0;
    }
    depcost += -cheap[i].top().first;
  }
  memset(minarr, -1, sizeof(minarr));
  int num = 0;
  long long ans = -1;
  while (!arr.empty()) {
    flight f = arr.top();
    arr.pop();
    int u = f.f;
    if (minarr[u] == -1) {
      num++;
      minarr[u] = f.c;
      arrcost += f.c;
    } else if (f.c < minarr[u]) {
      arrcost += f.c - minarr[u];
      minarr[u] = f.c;
    }
    if (num < n) continue;
    bool done = 0;
    while (!dep.empty() && dep.top().d <= f.d + k) {
      flight df = dep.top();
      dep.pop();
      depcost -= -cheap[df.t].top().first;
      while (!cheap[df.t].empty() && cheap[df.t].top().second <= df.d)
        cheap[df.t].pop();
      if (cheap[df.t].empty()) {
        done = 1;
        break;
      }
      depcost += -cheap[df.t].top().first;
    }
    if (done) break;
    if (ans == -1 || arrcost + depcost < ans) {
      ans = arrcost + depcost;
    }
  }
  cout << ans << '\n';
}
