#include <bits/stdc++.h>
using namespace std;
const int maxn = 1e5 + 10;
const long long INF = 1e18;
struct flight {
  int d, city;
  bool in;
  long long c;
} a[maxn];
int n, m, k, depart, dest;
long long ans, s;
long long f[maxn][2];
int cnt;
long long mini[maxn];
bool cmp(flight a, flight b) { return a.d < b.d; }
int findday(int p) {
  if (a[m].d < p) return -1;
  int l = 1, r = m;
  while (l + 1 < r) {
    int mid = (l + r) >> 1;
    if (a[mid].d < p)
      l = mid;
    else
      r = mid;
  }
  return r;
}
int main() {
  scanf("%d%d%d", &n, &m, &k);
  for (int i = 1; i <= m; i++) {
    scanf("%d%d%d%I64d", &a[i].d, &depart, &dest, &a[i].c);
    if (dest == 0) {
      a[i].city = depart;
      a[i].in = true;
    } else {
      a[i].city = dest;
      a[i].in = false;
    }
    f[i][0] = f[i][1] = INF;
  }
  sort(a + 1, a + m + 1, cmp);
  cnt = 0;
  s = 0ll;
  for (int i = 1; i <= n; i++) mini[i] = INF;
  for (int i = 1; i <= m; i++) {
    if (a[i].in) {
      if (mini[a[i].city] == INF) {
        cnt++;
        mini[a[i].city] = a[i].c;
        s += a[i].c;
      } else if (mini[a[i].city] > a[i].c) {
        s -= mini[a[i].city] - a[i].c;
        mini[a[i].city] = a[i].c;
      }
    }
    if (cnt == n) f[i][0] = s;
  }
  cnt = 0;
  s = 0ll;
  for (int i = 1; i <= n; i++) mini[i] = INF;
  for (int i = m; i >= 1; i--) {
    if (!a[i].in) {
      if (mini[a[i].city] == INF) {
        cnt++;
        mini[a[i].city] = a[i].c;
        s += a[i].c;
      } else if (mini[a[i].city] > a[i].c) {
        s -= mini[a[i].city] - a[i].c;
        mini[a[i].city] = a[i].c;
      }
    }
    if (cnt == n) f[i][1] = s;
  }
  ans = INF;
  for (int i = 1; i <= m; i++) {
    if (f[i][0] != INF) {
      int q = findday(a[i].d + k + 1);
      if (q == -1 || f[q][1] == INF) break;
      ans = min(ans, f[i][0] + f[q][1]);
    }
  }
  printf("%I64d\n", ans == INF ? -1ll : ans);
  return 0;
}
