#include <bits/stdc++.h>
using namespace std;
int D[110001 + 2];
int F[110001 + 2];
int T[110001 + 2];
long long C[110001 + 2];
set<pair<int, int> > fwd[110001 + 2];
vector<int> fwdv[1100000 + 2];
set<pair<int, int> > bck[110001 + 2];
vector<int> bckv[1100000 + 2];
long long Solve(int n, int m, int k) {
  for (int i = 1; i <= n; i++) {
    fwd[i].clear();
    bck[i].clear();
  }
  int MAXD = 1;
  for (int i = 1; i <= m; i++) MAXD = max(MAXD, D[i]);
  for (int i = 1; i <= m; i++) {
    if (T[i] == 0) {
      fwdv[D[i]].push_back(i);
    } else if (F[i] == 0) {
      bckv[D[i]].push_back(i);
    } else {
      exit(-1);
    }
  }
  for (int i = 1; i <= m; i++) {
    if (T[i] == 0 && D[i] + k + 1 <= MAXD) {
      fwd[F[i]].insert({C[i], i});
    }
  }
  long long fwd_sum = 0;
  for (int i = 1; i <= n; i++) {
    if (fwd[i].empty()) return -1;
    fwd_sum += fwd[i].begin()->first;
  }
  for (int i = 1; i <= m; i++) {
    if (F[i] == 0 && D[i] >= MAXD) {
      bck[T[i]].insert({C[i], i});
    }
  }
  int num_empty = 0;
  long long bck_sum = 0;
  for (int i = 1; i <= n; i++) {
    if (!bck[i].empty())
      bck_sum += bck[i].begin()->first;
    else
      num_empty++;
  }
  long long ans = (1ll << 60) + 100;
  bool done = false;
  for (int d = MAXD - k - 1; d >= 1; d--) {
    if (num_empty == 0) {
      ans = min(ans, fwd_sum + bck_sum);
    }
    for (int id : fwdv[d]) {
      fwd_sum -= fwd[F[id]].begin()->first;
      fwd[F[id]].erase({C[id], id});
      if (fwd[F[id]].empty()) {
        done = true;
        break;
      }
      fwd_sum += fwd[F[id]].begin()->first;
    }
    if (done) break;
    for (int id : bckv[d + k]) {
      if (!bck[T[id]].empty()) {
        bck_sum -= bck[T[id]].begin()->first;
      } else {
        num_empty--;
      }
      bck[T[id]].insert({C[id], id});
      bck_sum += bck[T[id]].begin()->first;
    }
  }
  if (ans >= (1ll << 60)) return -1;
  return ans;
}
int main() {
  int n, m, k;
  cin >> n >> m >> k;
  for (int i = 1; i <= m; i++) {
    cin >> D[i] >> F[i] >> T[i] >> C[i];
  }
  cout << Solve(n, m, k) << endl;
}
