#include <bits/stdc++.h>
using namespace std;
template <typename T>
inline T abs(T t) {
  return t < 0 ? -t : t;
}
const long long modn = 1000000007;
inline long long mod(long long x) { return x % modn; }
const int MAXN = 2123456;
const long long INF = 300000000000LL;
int n, m, k;
long long s[MAXN];
multiset<long long> bef[MAXN], aft[MAXN];
int ind[MAXN];
int d[MAXN], ini[MAXN], fim[MAXN];
vector<pair<int, long long> > in[MAXN], out[MAXN];
bool cmp(int a, int b) { return d[a] < d[b]; }
long long sum;
void add(int i, int j, long long x) {
  if (i == 0) {
    sum -= *aft[j].begin();
    aft[j].insert(x);
    sum += *aft[j].begin();
  } else {
    sum -= *bef[i].begin();
    bef[i].insert(x);
    sum += *bef[i].begin();
  }
}
void rmv(int i, int j, long long x) {
  if (i == 0) {
    sum -= *aft[j].begin();
    aft[j].erase(aft[j].find(x));
    sum += *aft[j].begin();
  } else {
    sum -= *bef[i].begin();
    bef[i].erase(bef[i].find(x));
    sum += *bef[i].begin();
  }
}
int main() {
  scanf("%d%d%d", &n, &m, &k);
  for (int a = 1; a <= n; a++) {
    bef[a].insert(INF);
    aft[a].insert(INF);
    sum += 2ll * INF;
  }
  for (int a = 0; a < m; a++) {
    scanf("%d%d%d%lld", &d[a], ini + a, fim + a, s + a);
    if (ini[a] == 0)
      out[d[a]].push_back(pair<int, long long>(fim[a], s[a]));
    else
      in[d[a]].push_back(pair<int, long long>(ini[a], s[a]));
  }
  for (int dia = 1000000; dia >= k; dia--) {
    for (int i = 0; i < out[dia].size(); i++) {
      pair<int, long long> voo = out[dia][i];
      add(0, voo.first, voo.second);
    }
  }
  long long res = LLONG_MAX;
  for (int dia = 0; dia <= 1000000 - k; dia++) {
    res = min(res, sum);
    for (pair<int, long long> voo : in[dia]) add(voo.first, 0, voo.second);
    for (pair<int, long long> voo : out[dia + k]) rmv(0, voo.first, voo.second);
  }
  if (res >= INF)
    puts("-1");
  else
    printf("%lld\n", res);
}
