#include <bits/stdc++.h>
using namespace std;
inline int read() {
  int x = 0, f = 1;
  char ch = getchar();
  while (ch < '0' || ch > '9') {
    if (ch == '-') f = -1;
    ch = getchar();
  }
  while (ch <= '9' && ch >= '0') {
    x = x * 10 + ch - '0';
    ch = getchar();
  }
  return x * f;
}
struct node {
  int t, de, te, c;
} data[1100000];
inline bool cmp(node a, node b) { return a.t < b.t; }
int min1[1100000], s, n, m, k, t;
long long dp[1100000], dp1[1100000], ans;
int main() {
  n = read();
  m = read();
  k = read();
  for (int i = 1; i <= m; ++i) {
    data[i].t = read();
    data[i].de = read();
    data[i].te = read();
    data[i].c = read();
    t = max(t, data[i].t);
  }
  sort(data + 1, data + m + 1, cmp);
  for (int i = 1; i <= t; ++i) dp[i] = 1LL << 60;
  int tot = 0;
  long long sum = 0;
  for (int i = 1; i <= m; ++i) {
    if (data[i].de == 0) continue;
    int de = data[i].de, cost = data[i].c;
    if (min1[de] == 0)
      min1[de] = cost, tot++, sum += cost;
    else if (cost < min1[de])
      sum -= min1[de], min1[de] = cost, sum += cost;
    if (tot == n) dp[data[i].t] = sum;
  }
  s = 1;
  while (s < t - 1 && dp[s] == 1LL << 60) ++s;
  if (s >= t - 1) {
    printf("-1");
    return 0;
  }
  for (int i = s + 1; i <= t - 2; ++i) dp[i] = min(dp[i], dp[i - 1]);
  for (int i = 1; i <= t; ++i) dp1[i] = 1LL << 60;
  tot = sum = 0;
  memset(min1, 0, sizeof(min1));
  for (int i = m; i >= 1; --i) {
    if (data[i].te == 0) continue;
    int te = data[i].te, cost = data[i].c;
    if (min1[te] == 0)
      min1[te] = cost, tot++, sum += cost;
    else if (cost < min1[te])
      sum -= min1[te], min1[te] = cost, sum += cost;
    if (tot == n) dp1[data[i].t] = sum;
  }
  s = t;
  while (s > 0 && dp[s] == 1LL << 60) --s;
  if (s < 1) {
    printf("-1");
    return 0;
  }
  for (int i = s - 1; i >= 1; --i) dp1[i] = min(dp1[i], dp1[i + 1]);
  ans = 1LL << 60;
  for (int i = 1; i + k + 1 <= t; ++i) {
    if (dp[i] == 1LL << 60 || dp1[i + k + 1] == 1LL << 60) continue;
    ans = min(ans, dp[i] + dp1[i + k + 1]);
  }
  if (ans == 1LL << 60)
    printf("-1");
  else
    printf("%lld", ans);
  return 0;
}
