#include <bits/stdc++.h>
using namespace std;
long long pre[1000010];
long long suf[1000010];
int cost[100010];
int see[100010];
vector<int> f[1000010], t[1000010], c[1000010];
const int maxn = 1000000;
const int inf = 1e9;
const long long INF = 1e16;
int main(int argc, char *argv[]) {
  int n, m, k;
  scanf("%d %d %d", &n, &m, &k);
  for (int i = 1; i <= m; i++) {
    int D, F, T, C;
    scanf("%d %d %d %d", &D, &F, &T, &C);
    f[D].push_back(F);
    t[D].push_back(T);
    c[D].push_back(C);
  }
  long long sum = 0;
  int tot = 0;
  for (int i = 1; i <= n; i++) {
    see[i] = 0;
    cost[i] = inf;
    sum += inf;
  }
  for (int i = 1; i <= maxn; i++) {
    for (size_t j = 0; j < f[i].size(); j++) {
      int F = f[i][j];
      int T = t[i][j];
      int C = c[i][j];
      if (F == 0) continue;
      if (see[F] == 0) ++tot;
      see[F] = 1;
      sum -= cost[F];
      cost[F] = min(cost[F], C);
      sum += cost[F];
    }
    if (tot < n)
      pre[i] = -1;
    else
      pre[i] = sum;
  }
  sum = 0;
  tot = 0;
  for (int i = 1; i <= n; i++) {
    see[i] = 0;
    cost[i] = inf;
    sum += inf;
  }
  for (int i = maxn; i >= 1; i--) {
    for (size_t j = 0; j < f[i].size(); j++) {
      int F = f[i][j];
      int T = t[i][j];
      int C = c[i][j];
      if (T == 0) continue;
      if (see[T] == 0) ++tot;
      see[T] = 1;
      sum -= cost[T];
      cost[T] = min(cost[T], C);
      sum += cost[T];
    }
    if (tot < n)
      suf[i] = -1;
    else
      suf[i] = sum;
  }
  long long ans = INF;
  for (int i = 1; i <= maxn; i++) {
    if (i + k + 1 > maxn) continue;
    if (pre[i] == -1 || suf[i + k + 1] == -1) continue;
    ans = min(ans, pre[i] + suf[i + k + 1]);
  }
  if (ans == INF) ans = -1;
  printf("%lld\n", ans);
  return 0;
}
