#include <bits/stdc++.h>
using namespace std;
const long long INF = 1e15;
const double eps = 1e-8;
template <typename T>
inline void read(T &x) {
  x = 0;
  int f = 1;
  char ch = getchar();
  while ((ch < '0' || ch > '9') && ch != '-') ch = getchar();
  if (ch == '-') {
    f = -1;
    ch = getchar();
  }
  while (ch >= '0' && ch <= '9') x = x * 10 + ch - '0', ch = getchar();
  x *= f;
}
const long long N = 100010, K = 1000010;
long long Mx_d;
struct FLIGHT {
  long long day, fr, to, co;
  inline void in() {
    read(day);
    read(fr);
    read(to);
    read(co);
    Mx_d = max(Mx_d, day);
  }
  inline void print() { printf("%lld %lld %lld %lld\n", day, fr, to, co); }
  bool operator<(const FLIGHT &a) const { return day < a.day; }
} fl[N];
long long n, m, k;
long long cost[N];
long long res[K];
signed main() {
  read(n);
  read(m);
  read(k);
  for (long long i = 1; i <= m; i++) {
    fl[i].in();
  }
  sort(fl + 1, fl + m + 1);
  memset(cost, -1, sizeof cost);
  memset(res, -1, sizeof res);
  long long cur = m, cnt = 0, ret = 0;
  for (long long i = Mx_d; i >= 1; i--) {
    while ((fl[cur].to == 0 || fl[cur].day >= i) && cur > 1) {
      long long co = fl[cur].co, to = fl[cur].to;
      if (!to) {
        --cur;
        continue;
      }
      if (cost[to] == -1) {
        ++cnt;
        cost[to] = co;
        ret += co;
      } else if (cost[to] > co) {
        ret -= cost[to] - co;
        cost[to] = co;
      }
      --cur;
    }
    res[i] = (cnt == n ? ret : -1);
  }
  cur = 1;
  memset(cost, -1, sizeof cost);
  cnt = 0;
  ret = 0;
  long long ans = INF;
  for (long long i = 1; i <= m; i++) {
    while (fl[i].to != 0 && i <= m) {
      ++i;
    }
    if (i > m) break;
    long long day = fl[i].day, co = fl[i].co, to = fl[i].fr;
    if (cost[to] == -1) {
      ++cnt;
      cost[to] = co;
      ret += co;
    } else if (cost[to] > co) {
      ret -= cost[to] - co;
      cost[to] = co;
    }
    if (day + k + 1 <= 1000000 && cnt == n && res[day + k + 1] != -1)
      ans = min(ans, ret + res[day + k + 1]);
  }
  if (ans == INF)
    puts("-1");
  else
    printf("%lld\n", ans);
  return 0;
}
