#include <bits/stdc++.h>
using namespace std;
int n, m, k;
long long dp[2][1000005];
long long need[2][1000005];
struct node {
  int d, f, t, c;
} a[100005];
int cmp(node u, node v) { return u.d < v.d; }
const long long inf = 0x3f3f3f3f3f3f3f3f;
int main() {
  int i;
  cin >> n >> m >> k;
  for (i = 0; i < m; i++) {
    scanf("%d %d %d %d", &a[i].d, &a[i].f, &a[i].t, &a[i].c);
  }
  sort(a, a + m, cmp);
  memset(need, -1, sizeof(need));
  memset(dp, inf, sizeof(dp));
  long long sum = 0, now = 0;
  for (i = 0; i < m; i++) {
    if (a[i].f) {
      if (need[0][a[i].f] == -1) {
        now++;
        sum += a[i].c;
        need[0][a[i].f] = a[i].c;
      } else if (a[i].c < need[0][a[i].f]) {
        sum += a[i].c - need[0][a[i].f];
        need[0][a[i].f] = a[i].c;
      }
      if (now == n) {
        dp[0][a[i].d] = min(dp[0][a[i].d], sum);
      }
    }
  }
  now = 0, sum = 0;
  for (i = m - 1; i >= 0; i--) {
    if (a[i].t) {
      if (need[1][a[i].t] == -1) {
        now++;
        sum += a[i].c;
        need[1][a[i].t] = a[i].c;
      } else if (a[i].c < need[1][a[i].t]) {
        sum += a[i].c - need[1][a[i].t];
        need[1][a[i].t] = a[i].c;
      }
      if (now == n) {
        dp[1][a[i].d] = min(dp[1][a[i].d], sum);
      }
    }
  }
  for (i = 1; i <= 1000000; i++) {
    dp[0][i] = min(dp[0][i], dp[0][i - 1]);
  }
  for (i = 1000000; i >= 0; i--) {
    dp[1][i] = min(dp[1][i], dp[1][i + 1]);
  }
  long long ans = inf;
  for (i = 0; i + k <= 1000000; i++) {
    ans = min(ans, dp[0][i] + dp[1][i + k + 1]);
  }
  if (ans == inf)
    cout << -1 << endl;
  else
    cout << ans << endl;
  return 0;
}
