#include <bits/stdc++.h>
using namespace std;
const int max_N = 1e5 + 10;
const int max_D = 1e6 + 10;
const long long inf = 1e13 + 5;
struct flight {
  long long day, from, to, cost;
  bool operator<(const flight &other) const { return (day < other.day); }
};
vector<flight> from, to;
long long rsc[max_N], lsc[max_N];
vector<flight> rse;
int main() {
  int N, M, K;
  scanf("%d%d%d", &N, &M, &K);
  for (int i = 1; i <= M; ++i) {
    flight temp;
    scanf("%lld%lld%lld%lld", &temp.day, &temp.from, &temp.to, &temp.cost);
    if (temp.from == 0) {
      from.push_back(temp);
    } else {
      to.push_back(temp);
    }
  }
  sort(from.begin(), from.end());
  reverse(from.begin(), from.end());
  sort(to.begin(), to.end());
  for (int i = 1; i <= N; ++i) {
    rsc[i] = inf;
    lsc[i] = inf;
  }
  for (auto &x : from) {
    if (x.cost < rsc[x.to]) {
      rse.push_back({x.day, 0, x.to, rsc[x.to]});
      rsc[x.to] = x.cost;
    }
  }
  reverse(rse.begin(), rse.end());
  long long ans = inf;
  long long curr = 0;
  for (int i = 1; i <= N; ++i) {
    curr += lsc[i] + rsc[i];
  }
  auto it1 = to.begin(), it2 = rse.begin();
  for (int sp = 1; sp < max_D; ++sp) {
    int ep = sp + K - 1;
    while (it1 != to.end() && it1->day < sp) {
      if (it1->cost < lsc[it1->from]) {
        curr += it1->cost - lsc[it1->from];
        lsc[it1->from] = it1->cost;
      }
      ++it1;
    }
    while (it2 != rse.end() && it2->day <= ep) {
      curr += it2->cost - rsc[it2->to];
      rsc[it2->to] = it2->cost;
      ++it2;
    }
    ans = min(ans, curr);
  }
  if (ans == inf) {
    cout << -1 << endl;
  } else {
    cout << ans << endl;
  }
}
