#include <bits/stdc++.h>
using namespace std;
const long long inf = 1e18;
const long long sz = 1e6 + 150;
struct ticket {
  long long tm, from, to, price;
};
bool cmp(ticket a, ticket b) { return a.tm < b.tm; }
vector<long long> arrive(sz + 150, inf), leave(sz + 150, inf);
long long n, m, k;
vector<long long> used(sz + 100, inf);
vector<ticket> a;
int main() {
  cin >> n >> m >> k;
  ticket temp;
  long long i;
  for (i = 0; i < m; i++) {
    cin >> temp.tm >> temp.from >> temp.to >> temp.price;
    if (temp.from == 0)
      temp.tm--;
    else
      temp.tm++;
    a.push_back(temp);
  }
  sort(a.begin(), a.end(), cmp);
  long long sum = 0, num = 0;
  for (i = 0; i < m; i++) {
    ticket cur = a[i];
    if (cur.from != 0) {
      if (used[cur.from] == inf) {
        sum += cur.price;
        num++;
        used[cur.from] = cur.price;
      } else {
        if (used[cur.from] > cur.price) {
          sum -= used[cur.from];
          sum += cur.price;
          used[cur.from] = cur.price;
        }
      }
      if (num == n) arrive[cur.tm] = min(arrive[cur.tm], sum);
    }
  }
  for (i = 0; i <= sz + 10; i++) used[i] = inf;
  arrive[0] = inf;
  for (i = 1; i <= sz + 100; i++) arrive[i] = min(arrive[i], arrive[i - 1]);
  reverse(a.begin(), a.end());
  sum = 0, num = 0;
  for (i = 0; i < m; i++) {
    ticket cur = a[i];
    if (cur.to != 0) {
      if (used[cur.to] == inf) {
        sum += cur.price;
        num++;
        used[cur.to] = cur.price;
      } else {
        if (used[cur.to] > cur.price) {
          sum -= used[cur.to];
          sum += cur.price;
          used[cur.to] = cur.price;
        }
      }
      if (num == n) leave[cur.tm] = min(leave[cur.tm], sum);
    }
  }
  leave[sz + 10] - inf;
  for (i = sz + 9; i >= 1; i--) leave[i] = min(leave[i], leave[i + 1]);
  long long best = inf;
  for (i = 1; i <= sz; i++) {
    long long j = i + k - 1;
    if (j > sz) break;
    best = min(best, arrive[i] + leave[j]);
  }
  if (best < inf)
    cout << best;
  else
    cout << -1;
  return 0;
}
