#include <bits/stdc++.h>
using namespace std;
const int N = 1e6 + 100;
const long long INF = 1e18;
struct node {
  long long d, f, t, c;
} a[N];
long long b[N];
long long dp[1000006], dp1[1000005];
bool cmp(node p, node q) { return p.d < q.d; }
int main() {
  int n, m, k;
  long long x = 1000000, y = -1;
  cin >> n >> m >> k;
  for (int i = 1; i <= m; i++) {
    scanf("%lld%lld%lld%lld", &a[i].d, &a[i].f, &a[i].t, &a[i].c);
  }
  sort(a + 1, a + 1 + m, cmp);
  for (int i = 1; i <= 1000001; i++) b[i] = -1, dp[i] = INF;
  long long sum = 0, s = 0;
  for (int i = 1; i <= m; i++) {
    if (a[i].f == 0) continue;
    if (b[a[i].f] == -1) {
      s++;
      b[a[i].f] = a[i].c;
      sum += 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 (s == n) {
      dp[a[i].d] = sum;
      x = min(x, a[i].d);
    }
  }
  for (int i = 1; i <= 1000001; i++) b[i] = -1, dp1[i] = INF;
  sum = 0;
  s = 0;
  for (int i = m; i >= 1; i--) {
    if (a[i].t == 0) continue;
    if (b[a[i].t] == -1) {
      s++;
      b[a[i].t] = a[i].c;
      sum += 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 (s == n) {
      dp1[a[i].d] = sum;
      y = max(y, a[i].d);
    }
  }
  for (int i = x + 1; i <= 1000000; i++) dp[i] = min(dp[i - 1], dp[i]);
  for (int i = y - 1; i >= 1; i--) dp1[i] = min(dp1[i + 1], dp1[i]);
  long long ans = INF;
  for (int i = 1; i <= 1000000 - k - 1; i++) {
    if (dp[i] == INF || dp1[i + k + 1] == INF) continue;
    if (ans > dp[i] + dp1[i + k + 1]) {
      ans = dp[i] + dp1[i + k + 1];
    }
  }
  if (ans == INF)
    cout << -1 << endl;
  else
    cout << ans << endl;
}
