#include <bits/stdc++.h>
using namespace std;
const int INF = 0x3f3f3f;
const int MAXN = 1e5 + 10;
const int MAXM = 1e6 + 10;
long long b[MAXN];
long long dp1[MAXM], dp2[MAXM];
struct node {
  long long d, f, t, c;
} a[MAXN];
bool cmp(node x, node y) { return x.d < y.d; }
int main() {
  int n, m, k;
  scanf("%d%d%d", &n, &m, &k);
  for (int i = 0; i < m; i++)
    scanf("%lld%lld%lld%lld", &a[i].d, &a[i].f, &a[i].t, &a[i].c);
  sort(a, a + m, cmp);
  memset((b), (-1), sizeof(b));
  for (int i = 0; i < MAXM; i++) {
    dp1[i] = 1e17;
    dp2[i] = 1e17;
  }
  int num = 0;
  long long sum = 0;
  for (int i = 0; i < m; i++) {
    if (a[i].f == 0) continue;
    if (b[a[i].f] == -1) {
      num++;
      sum += a[i].c;
      b[a[i].f] = a[i].c;
    } else {
      if (b[a[i].f] > a[i].c) {
        sum -= b[a[i].f];
        sum += a[i].c;
        b[a[i].f] = a[i].c;
      }
    }
    if (num == n) dp1[a[i].d] = sum;
  }
  memset((b), (-1), sizeof(b));
  num = 0;
  sum = 0;
  for (int i = m - 1; i >= 0; i--) {
    if (a[i].t == 0) continue;
    if (b[a[i].t] == -1) {
      num++;
      sum += a[i].c;
      b[a[i].t] = a[i].c;
    } else {
      if (b[a[i].t] > a[i].c) {
        sum -= b[a[i].t];
        sum += a[i].c;
        b[a[i].t] = a[i].c;
      }
    }
    if (num == n) dp2[a[i].d] = sum;
  }
  for (int i = 1; i < MAXM; i++) dp1[i] = min(dp1[i], dp1[i - 1]);
  for (int i = MAXM - 2; i >= 0; i--) dp2[i] = min(dp2[i], dp2[i + 1]);
  long long ans = 1e17;
  for (int i = 0; i < MAXM - k - 1; i++) {
    if (dp1[i] == 1e17 || dp2[i + k + 1] == 1e17) continue;
    ans = min(ans, dp1[i] + dp2[i + k + 1]);
  }
  if (ans == 1e17) ans = -1;
  printf("%lld\n", ans);
  return 0;
}
