#include <bits/stdc++.h>
using namespace std;
struct flight {
  int u, v, c;
  flight(int U, int V, int C) : u(U), v(V), c(C) {}
};
int n, m, k;
long long pre[1111000], suf[1111000], best[1111000], INF = 15e11, tot;
vector<flight> vet[1111000];
int main() {
  scanf("%d%d%d", &n, &m, &k);
  for (int(i) = (0); (i) < (m); (i)++) {
    int d, u, v, c;
    scanf("%d%d%d%d", &d, &u, &v, &c);
    vet[d].push_back(flight(u, v, c));
  }
  tot = INF * n;
  pre[0] = tot;
  for (int(i) = (1); (i) < (n + 1); (i)++) best[i] = INF;
  for (int(i) = (1); (i) < (1111000); (i)++) {
    for (int(j) = (0); (j) < (((int)(vet[i]).size())); (j)++)
      if (vet[i][j].u) {
        int u = vet[i][j].u, c = vet[i][j].c;
        tot -= best[u];
        best[u] = min(best[u], (long long)c);
        tot += best[u];
      }
    pre[i] = tot;
  }
  tot = INF * n;
  suf[1111000 - 1] = tot;
  for (int(i) = (1); (i) < (n + 1); (i)++) best[i] = INF;
  for (int(i) = (1111000 - 2); (i) >= (0); (i)--) {
    for (int(j) = (0); (j) < (((int)(vet[i]).size())); (j)++)
      if (vet[i][j].v) {
        int v = vet[i][j].v, c = vet[i][j].c;
        tot -= best[v];
        best[v] = min(best[v], (long long)c);
        tot += best[v];
      }
    suf[i] = tot;
  }
  long long ans = INF;
  for (int(i) = (0); (i) < (1111000 - 10 - k); (i)++)
    ans = min(ans, pre[i] + suf[k + i + 1]);
  if (ans == INF)
    puts("-1");
  else
    printf("%lld\n", ans);
}
