#include <bits/stdc++.h>
using namespace std;
pair<int, int> dirs[4] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
void setIO(string name = "") {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  if (name.length()) {
    freopen((name + ".in").c_str(), "r", stdin);
    freopen((name + ".out").c_str(), "w", stdout);
  }
}
int n, m, k;
struct flight {
  int t, a, b, cost;
};
bool tcmp(const flight& a, const flight& b) {
  if (a.t == b.t) return a.a > b.a;
  return a.t < b.t;
}
flight A[100000];
void solve() {
  cin >> n >> m >> k;
  for (int i = 0; i < m; i++) {
    int d, a, b, c;
    cin >> d >> a >> b >> c;
    A[i] = {d, a, b, c};
  }
  sort(A, A + m, tcmp);
  int u = -1, v = -1;
  int cnt = 0;
  map<int, long long> gcost, fcost;
  long long lcost = 0, rcost = 0;
  for (int i = 0; i < m; i++) {
    if (A[i].b == 0) {
      if (gcost.count(A[i].a)) {
        if (gcost[A[i].a] > A[i].cost)
          lcost -= gcost[A[i].a], gcost[A[i].a] = A[i].cost,
                                  lcost += gcost[A[i].a];
      } else {
        gcost[A[i].a] = A[i].cost, lcost += A[i].cost;
        if (++cnt == n) {
          u = i;
          break;
        }
      }
    }
  }
  if (u == -1) {
    cout << -1 << endl;
    return;
  }
  vector<long long> sufcost(m + 1, LLONG_MAX);
  cnt = 0;
  int i = m - 1;
  for (i = m - 1; i > u; i--) {
    if (A[i].a == 0) {
      if (fcost.count(A[i].b)) {
        if (fcost[A[i].b] > A[i].cost)
          rcost -= fcost[A[i].b], fcost[A[i].b] = A[i].cost,
                                  rcost += fcost[A[i].b];
      } else {
        fcost[A[i].b] = A[i].cost, rcost += A[i].cost;
        if (++cnt == n) {
          for (int j = i; j <= m; j++) sufcost[j] = rcost;
          v = i;
          i--;
          break;
        }
      }
    }
  }
  if (v == -1) {
    cout << -1 << endl;
    return;
  }
  for (; i > u; i--) {
    sufcost[i] = sufcost[i + 1];
    if (A[i].a == 0 && fcost[A[i].b] > A[i].cost) {
      rcost -= fcost[A[i].b], fcost[A[i].b] = A[i].cost, rcost += A[i].cost;
      sufcost[i] = rcost;
    }
  }
  long long res = -1;
  int r = u;
  for (i = u; i <= v; i++) {
    while (r <= v && A[i].t + k >= A[r].t) r++;
    if (r > v) break;
    if (A[i].b == 0 && gcost[A[i].a] > A[i].cost) {
      lcost -= gcost[A[i].a], gcost[A[i].a] = A[i].cost, lcost += gcost[A[i].a];
    }
    if (res == -1)
      res = lcost + sufcost[r];
    else
      res = min(res, lcost + sufcost[r]);
  }
  cout << res << endl;
}
int main() {
  setIO("");
  int T = 1;
  while (T--) {
    solve();
  }
  return 0;
}
