#include <bits/stdc++.h>
using namespace std;
bool visited[1000000 + 10];
long long int costin[1000000 + 10], dpin[1000000 + 10];
long long int costout[1000000 + 10], dpout[1000000 + 10];
void fun() {
  for (int i = 0; i < 1000000 + 5; i++) {
    dpin[i] = -1;
    dpout[i] = -1;
  }
}
int main() {
  fun();
  int n, m, k, a, b, c, d;
  vector<pair<int, pair<int, int> > > vin, vout;
  cin >> n >> m >> k;
  for (int i = 0; i < m; i++) {
    scanf("%d %d %d %d", &a, &b, &c, &d);
    if (c == 0) {
      vin.push_back(make_pair(a, make_pair(b, d)));
    } else {
      vout.push_back(make_pair(a, make_pair(c, d)));
    }
  }
  sort(vin.begin(), vin.end());
  sort(vout.begin(), vout.end(), greater<pair<int, pair<int, int> > >());
  long long int val = 0, indate = -1, outdate = -1, ct = 0;
  for (int i = 0; i < vin.size(); i++) {
    int date = vin[i].first, city = vin[i].second.first,
        cst = vin[i].second.second;
    if (!visited[city]) {
      costin[city] = cst;
      val += costin[city];
      ct++;
      visited[city] = 1;
    } else if (visited[city]) {
      if (costin[city] > cst) {
        val -= costin[city] - cst;
        costin[city] = cst;
      }
    }
    dpin[date] = val;
    if (ct == n && indate == -1) indate = date;
  }
  for (int i = 1; i <= 1000000; i++) {
    if (dpin[i] == -1) dpin[i] = dpin[i - 1];
  }
  for (int i = 0; i <= 1000000 + 4; i++) {
    visited[i] = 0;
  }
  val = 0, ct = 0;
  for (int i = 0; i < vout.size(); i++) {
    int date = vout[i].first, city = vout[i].second.first,
        cst = vout[i].second.second;
    if (!visited[city]) {
      costout[city] = cst;
      val += costout[city];
      ct++;
      visited[city] = 1;
    } else if (visited[city]) {
      if (costout[city] > cst) {
        val -= costout[city] - cst;
        costout[city] = cst;
      }
    }
    dpout[date] = val;
    if (ct == n && outdate == -1) {
      outdate = date;
    }
  }
  for (int i = 1e6; i >= 0; i--) {
    if (dpout[i] == -1) dpout[i] = dpout[i + 1];
  }
  long long int ans = -1;
  if (indate != -1 && outdate != -1 && indate + k < outdate) {
    for (int i = indate; i <= outdate - k - 1; i++) {
      if (ans == -1) {
        ans = dpin[i] + dpout[i + k + 1];
      } else {
        ans = min(ans, dpin[i] + dpout[i + k + 1]);
      }
    }
    cout << ans;
  } else
    cout << "-1";
}
