#include <bits/stdc++.h>
using namespace std;
long long w[2050000], a[2050000], w1[2050000], b[2050000];
long long n, m, k;
struct node {
  long long t;
  long long x;
  long long y;
  long long money;
} f[2050000];
bool cmp(node x, node y) {
  if (x.y == 0 && y.y != 0) {
    return true;
  } else if (x.y != 0 && y.y == 0) {
    return false;
  } else
    return x.t < y.t;
}
int main() {
  long long maxx = 0;
  scanf("%I64d%I64d%I64d", &n, &m, &k);
  for (int i = 0; i < m; i++) {
    scanf("%I64d%I64d%I64d%I64d", &f[i].t, &f[i].x, &f[i].y, &f[i].money);
  }
  for (long long i = 0; i < 2050000; i++) {
    w[i] = 100010000000;
    w1[i] = 100010000000;
  }
  maxx = (long long)1 * 100010000000 * n;
  int len1 = 0;
  sort(f, f + m, cmp);
  int i = 0;
  for (i; i < m; i++) {
    if (f[i].y != 0) {
      break;
    }
    if (f[i].money <= w[f[i].x]) {
      long long k = w[f[i].x] - f[i].money;
      maxx -= k;
      w[f[i].x] = f[i].money;
      a[f[i].t] = maxx;
      len1 = f[i].t;
    }
  }
  maxx = (long long)1 * 100010000000 * n;
  int sum = 0;
  int len2 = f[m - 1].t;
  for (int j = m - 1; j >= i; j--) {
    if (f[j].money <= w1[f[j].y]) {
      long long k = w1[f[j].y] - f[j].money;
      maxx -= k;
      w1[f[j].y] = f[j].money;
      b[f[j].t] = maxx;
    }
  }
  a[0] = -1;
  for (i = 1; i < 2050000; i++) {
    if (!a[i]) {
      a[i] = a[i - 1];
    }
    if (a[i] >= 100010000000) {
      a[i] = -1;
    }
  }
  for (int i = len2; i >= 0; i--) {
  }
  for (int i = 0; i < 2050000; i++) {
    if (a[i - 1] != -1) {
      a[i] = min(a[i - 1], a[i]);
    }
  }
  b[0] = -1;
  for (i = len2 - 1; i >= 0; i--) {
    if (b[i]) {
      b[i] = min(b[i + 1], b[i]);
    } else {
      b[i] = b[i + 1];
    }
  }
  long long ans = n * 100010000000;
  for (int i = 1; i + k + 1 <= len2; i++) {
    if (a[i] != -1 && b[i + k + 1] != -1) {
      ans = min(ans, a[i] + b[i + k + 1]);
    }
  }
  if (ans >= 100010000000 || ans < 0) {
    printf("-1");
  } else
    printf("%I64d\n", ans);
}
