#include <bits/stdc++.h>
using namespace std;
const int T = 1e6;
int d[100005], x[100005], c[100005], id[100005];
bool cmp(int a, int b) { return d[a] < d[b]; }
long long f[T + 6], r[T + 6], h[100005];
int main() {
  int i, j, k;
  int n, m, K;
  scanf("%d%d%d", &n, &m, &K);
  for (i = 1; i <= m; i++) {
    scanf("%d%d%d%d", d + i, x + i, &j, c + i);
    if (j) {
      d[i] += T;
      x[i] = j;
    }
    id[i] = i;
  }
  sort(id + 1, id + m + 1, cmp);
  long long ans = 1e12 * n;
  j = 1;
  fill(h + 1, h + n + 1, 1e12);
  for (i = 1; i <= T; i++) {
    while (d[k = id[j]] == i) {
      if (h[x[k]] > c[k]) {
        ans -= h[x[k]] - c[k];
        h[x[k]] = c[k];
      }
      j++;
    }
    f[i] = ans;
  }
  j = m;
  ans = 1e12 * n;
  fill(h + 1, h + n + 1, 1e12);
  for (i = T; i >= 1; i--) {
    while (d[k = id[j]] == i + T) {
      if (h[x[k]] > c[k]) {
        ans -= h[x[k]] - c[k];
        h[x[k]] = c[k];
      }
      j--;
    }
    r[i] = ans;
  }
  ans = 1e12;
  for (i = 1; i <= T - K - 1; i++) {
    ans = min(ans, f[i] + r[i + K + 1]);
  }
  printf("%I64d", ans == 1e12 ? -1 : ans);
  return 0;
}
