#include <bits/stdc++.h>
using namespace std;
void addmod(int &a, long long b) {
  a = (a + b);
  if (a >= 1000000007) a -= 1000000007;
}
void mulmod(int &a, long long b) { a = (a * b) % 1000000007; }
template <class T>
bool domin(T &a, const T &b) {
  return a > b ? a = b, 1 : 0;
}
template <class T>
bool domax(T &a, const T &b) {
  return a < b ? a = b, 1 : 0;
}
int gi() {
  int a;
  scanf("%d", &a);
  return a;
}
long long gll() {
  long long a;
  scanf("%lld", &a);
  return a;
}
vector<pair<int, long long> > arr[1000007], dep[1000007];
int main() {
  int n = gi(), m = gi(), k = gi();
  vector<long long> costarr(1000007, LLONG_MAX), costdep(1000007, LLONG_MAX);
  for (int i = 0; i < m; i++) {
    int dy = gi() - 1, di = gi(), ai = gi();
    long long c = gi();
    if (di == 0) {
      dep[dy - 1].push_back({ai - 1, c});
    } else {
      arr[dy + 1].push_back({di - 1, c});
    }
  }
  int tcnt = 0;
  long long rcost = 0;
  vector<bool> seen(n, false);
  vector<int> cost(n, 0);
  for (int i = 0; i < 1000007; i++) {
    for (auto j : arr[i]) {
      int ix = j.first;
      long long tco = j.second;
      if (seen[ix]) {
        if (tco < cost[ix]) {
          rcost += tco - cost[ix];
          cost[ix] = tco;
        }
      } else {
        seen[ix] = true;
        tcnt++;
        rcost += tco;
        cost[ix] = tco;
      }
    }
    if (tcnt == n) {
      costarr[i] = rcost;
    }
  }
  fill(seen.begin(), seen.end(), false);
  fill(cost.begin(), cost.end(), 0);
  tcnt = 0, rcost = 0;
  for (int i = 1000007 - 1; i >= 0; i--) {
    for (auto j : dep[i]) {
      int ix = j.first;
      long long tco = j.second;
      if (seen[ix]) {
        if (tco < cost[ix]) {
          rcost += tco - cost[ix];
          cost[ix] = tco;
        }
      } else {
        seen[ix] = true;
        tcnt++;
        rcost += tco;
        cost[ix] = tco;
      }
    }
    if (tcnt == n) {
      costdep[i] = rcost;
    }
  }
  long long ans = LLONG_MAX;
  for (int bg = 1; bg + k < 1000007; bg++) {
    if (costarr[bg] == LLONG_MAX || costdep[bg + k - 1] == LLONG_MAX) continue;
    domin(ans, costarr[bg] + costdep[bg + k - 1]);
  }
  if (ans == LLONG_MAX) ans = -1;
  cout << ans << endl;
  return 0;
}
