#include <bits/stdc++.h>
using namespace std;
const int maxx = 1000010;
priority_queue<long long, vector<long long>, greater<long long> >
    q[maxx / 10 + 10000];
long long t, n, m, k;
long long ans = 0, total = 0, sum = 0, cnt = 0, l = 0, l1 = 0, r1 = 0;
long long a[maxx], sum1[maxx], sum2[maxx], bj1[maxx], bj2[maxx];
struct node {
  long long d;
  long long f;
  long long t;
  long long c;
} s[maxx];
bool cmp(node a, node b) { return a.f > b.f; }
bool cm(node a, node b) {
  if (a.d == b.d) {
    if (a.f == b.f) return a.c < b.c;
    return a.f < b.f;
  }
  return a.d < b.d;
}
int main() {
  scanf("%lld%lld%lld", &n, &m, &k);
  if (m == 0) {
    printf("-1");
    return 0;
  }
  for (register int i = 1; i <= m; i++)
    scanf("%lld%lld%lld%lld", &s[i].d, &s[i].f, &s[i].t, &s[i].c);
  sort(s + 1, s + m + 1, cmp);
  for (register int i = 1; i <= m; i++)
    if (s[i].f == 0) {
      l = i;
      break;
    }
  sort(s + 1, s + l, cm);
  sort(s + l, s + m + 1, cm);
  for (register int i = 1; i <= l - 1; i++) {
    bj1[i] = bj1[i - 1];
    sum1[i] = sum1[i - 1];
    if (!q[s[i].f].size()) {
      bj1[i]++;
      q[s[i].f].push(s[i].c);
      sum1[i] += s[i].c;
    } else {
      sum1[i] -= q[s[i].f].top();
      q[s[i].f].push(s[i].c);
      sum1[i] += q[s[i].f].top();
    }
  }
  for (register int i = 1; i <= n; i++)
    while (!q[i].empty()) {
      q[i].pop();
    }
  for (register int i = m; i >= l; i--) {
    bj2[i] = bj2[i + 1];
    sum2[i] = sum2[i + 1];
    if (!q[s[i].t].size()) {
      bj2[i]++;
      q[s[i].t].push(s[i].c);
      sum2[i] += s[i].c;
    } else {
      sum2[i] -= q[s[i].t].top();
      q[s[i].t].push(s[i].c);
      sum2[i] += q[s[i].t].top();
    }
  }
  l1 = l - 1, r1 = l;
  if (bj1[l1] != n || bj2[r1] != n) {
    printf("-1");
    return 0;
  }
  ans = 1e16;
  sum = 0;
  while (l1 >= 1) {
    long long l2 = l, r2 = m, kl = 0;
    while (l2 <= r2) {
      long long mid = (l2 + r2) >> 1;
      if (bj2[mid] != n)
        r2 = mid - 1;
      else {
        if (s[mid].d - s[l1].d - 1 >= k) {
          kl = mid;
          r2 = mid - 1;
        } else
          l2 = mid + 1;
      }
    }
    if (kl) ans = min(ans, sum1[l1] + sum2[kl]);
    l1--, r1 = l;
    if (bj1[l1] != n) break;
  }
  if (ans == 1e16)
    printf("-1");
  else
    printf("%lld", ans);
  return 0;
}
