#include <bits/stdc++.h>
using namespace std;
const int maxn = 1e5 + 100;
const int maxL = 1e6 + 100;
struct Flight {
  int fr, to, cost;
  Flight(int a = 0, int b = 0, int c = 0) { fr = a, to = b, cost = c; }
};
int N, M, K, L;
int used[maxn];
long long pre[maxL], suf[maxL];
vector<Flight> ope[maxL];
void Prepare() {
  long long ret = 0;
  memset(used, 255, sizeof(used[0]) * (N + 2));
  int g = 0;
  for (int i = (1), _i = (L); i <= _i; i++) {
    for (int j = (0), _j = (ope[i].size() - 1); j <= _j; j++) {
      int fr = ope[i][j].fr, to = ope[i][j].to, cost = ope[i][j].cost;
      if (to != 0) continue;
      if (used[fr] == -1) {
        ++g;
        ret += cost;
        used[fr] = cost;
      } else if (cost < used[fr]) {
        ret -= used[fr] - cost;
        used[fr] = cost;
      }
    }
    pre[i] = (g == N ? ret : -1);
  }
  ret = 0;
  memset(used, 255, sizeof(used[0]) * (N + 2));
  g = 0;
  for (int i = (L), _i = (1); i >= _i; i--) {
    for (int j = (0), _j = (ope[i].size() - 1); j <= _j; j++) {
      int fr = ope[i][j].fr, to = ope[i][j].to, cost = ope[i][j].cost;
      if (fr != 0) continue;
      if (used[to] == -1) {
        ++g;
        ret += cost;
        used[to] = cost;
      } else if (cost < used[to]) {
        ret -= used[to] - cost;
        used[to] = cost;
      }
    }
    suf[i] = (g == N ? ret : -1);
  }
}
int main() {
  for (; scanf("%d%d%d", &N, &M, &K) != EOF;) {
    for (int i = (0), _i = (maxL - 1); i <= _i; i++) ope[i].clear();
    L = 0;
    for (int i = (1), _i = (M); i <= _i; i++) {
      int d, f, t, c;
      scanf("%d%d%d%d", &d, &f, &t, &c);
      ope[d].push_back(Flight(f, t, c));
      L = max(L, d);
    }
    Prepare();
    long long ans = -1;
    for (int i = (1), _i = (L - K - 1); i <= _i; i++) {
      int j = i + K + 1;
      if (pre[i] == -1 || suf[j] == -1) continue;
      if (ans == -1 || pre[i] + suf[j] < ans) ans = pre[i] + suf[j];
    }
    printf("%I64d\n", ans);
  }
  return 0;
}
