#include <bits/stdc++.h>
using namespace std;
struct _flight {
  int day;
  int from;
  int to;
  long long cost;
};
const long long DAY = 1000000;
const long long MAXN = 100000;
vector<long long> day[DAY + 10];
vector<_flight> F;
long long sum_come[DAY + 10] = {0};
long long cost_come[MAXN + 10] = {0};
long long sum_leave[DAY + 10] = {0};
long long cost_leave[MAXN + 10] = {0};
int early = MAXN + 5;
int late = 0;
bool b1 = false;
bool b2 = false;
int n, m, k;
int c = 0;
int main() {
  cin >> n >> m >> k;
  if (m < 2 * n) {
    cout << -1 << endl;
    return 0;
  }
  F.resize(m);
  for (int i = 0; i < m; i++) {
    cin >> F[i].day >> F[i].from >> F[i].to >> F[i].cost;
    day[F[i].day].push_back(i);
  }
  for (int i = 1; i <= DAY; i++) {
    sum_come[i] = sum_come[i - 1];
    if (day[i].empty()) {
      continue;
    }
    for (int j = 0; j < day[i].size(); j++) {
      _flight& f = F[day[i][j]];
      if (f.from == 0) continue;
      if (cost_come[f.from] == 0) {
        c++;
        if (c == n) {
          b1 = true;
          early = i;
        }
        sum_come[i] += f.cost;
        cost_come[f.from] = f.cost;
      } else {
        if (cost_come[f.from] > f.cost) {
          sum_come[i] -= cost_come[f.from] - f.cost;
          cost_come[f.from] = f.cost;
        }
      }
    }
  }
  for (int i = DAY; i >= 1; i--) {
    sum_leave[i] = sum_leave[i + 1];
    if (day[i].empty()) {
      continue;
    }
    for (int j = 0; j < day[i].size(); j++) {
      _flight& f = F[day[i][j]];
      if (f.to == 0) continue;
      if (cost_leave[f.to] == 0) {
        c--;
        if (c == 0) {
          b2 = true;
          late = i;
        }
        sum_leave[i] += f.cost;
        cost_leave[f.to] = f.cost;
      } else {
        if (cost_leave[f.to] > f.cost) {
          sum_leave[i] -= cost_leave[f.to] - f.cost;
          cost_leave[f.to] = f.cost;
        }
      }
    }
  }
  if (!b1 || !b2) {
    cout << -1 << endl;
    return 0;
  }
  bool ok = false;
  long long mi = 0x7fffffffffffffff;
  for (int i = early; i + k + 1 <= late; i++) {
    ok = true;
    mi = min(mi, sum_come[i] + sum_leave[i + k + 1]);
  }
  if (ok) {
    cout << mi << endl;
  } else {
    cout << -1 << endl;
  }
  return 0;
}
