#include <bits/stdc++.h>
using namespace std;
const long long INF = 1e12;
const int INF1 = 1e7;
const int maxn = 100000 + 10;
int n, m, k;
int fd, u, v, w;
struct node {
  int to, cost, fd;
} a[maxn], b[maxn];
bool cmp(node f, node g) { return f.fd < g.fd; }
bool cmp1(node f, node g) { return f.fd > g.fd; }
int ecnt = 0, ecnt1 = 0;
long long dp[maxn * 10], dp1[maxn * 10];
int d[maxn], d1[maxn];
int mx = 0;
int main() {
  scanf("%d%d%d", &n, &m, &k);
  for (int i = 1; i <= m; i++) {
    scanf("%d%d%d%d", &fd, &u, &v, &w);
    if (v == 0) {
      a[ecnt].to = u, a[ecnt].cost = w, a[ecnt].fd = fd;
      ecnt++;
    }
    if (u == 0) {
      b[ecnt1].to = v, b[ecnt1].cost = w, b[ecnt1].fd = fd;
      ecnt1++;
    }
    mx = max(mx, fd);
  }
  sort(a, a + ecnt, cmp);
  sort(b, b + ecnt1, cmp1);
  for (int i = 1; i <= n; i++) d[i] = INF1, d1[i] = INF1;
  int cnt = 0;
  int tmp = -1;
  for (int i = 0; i < ecnt; i++) {
    v = a[i].to;
    if (d[v] == INF1) {
      cnt++;
    }
    d[v] = min(d[v], a[i].cost);
    if (cnt == n) {
      tmp = i;
      break;
    }
  }
  if (tmp == -1) {
    printf("-1\n");
    return 0;
  }
  for (int i = 1; i <= n; i++) dp[a[tmp].fd] += d[i];
  for (int i = tmp + 1; i < ecnt; i++) {
    v = a[i].to;
    dp[a[i].fd] = dp[a[i - 1].fd];
    dp[a[i].fd] = dp[a[i].fd] - d[v];
    d[v] = min(d[v], a[i].cost);
    dp[a[i].fd] += d[v];
  }
  cnt = 0;
  tmp = -1;
  for (int i = 0; i < ecnt1; i++) {
    v = b[i].to;
    if (d1[v] == INF1) {
      cnt++;
    }
    d1[v] = min(d1[v], b[i].cost);
    if (cnt == n) {
      tmp = i;
      break;
    }
  }
  if (tmp == -1) {
    printf("-1\n");
    return 0;
  }
  for (int i = 1; i <= n; i++) dp1[b[tmp].fd] += d1[i];
  for (int i = tmp + 1; i < ecnt1; i++) {
    v = b[i].to;
    dp1[b[i].fd] = dp1[b[i - 1].fd];
    dp1[b[i].fd] = dp1[b[i].fd] - d1[v];
    d1[v] = min(d1[v], b[i].cost);
    dp1[b[i].fd] += d1[v];
  }
  for (int i = 1; i <= mx; i++) {
    if (dp[i] == 0) dp[i] = dp[i - 1];
  }
  for (int i = mx; i >= 1; i--) {
    if (dp1[i] == 0) dp1[i] = dp1[i + 1];
  }
  long long ans = INF;
  for (int i = 0; i < ecnt; i++) {
    if (dp[a[i].fd] != 0) {
      if (a[i].fd + k + 1 <= mx && dp1[a[i].fd + k + 1] != 0)
        ans = min(ans, dp[a[i].fd] + dp1[a[i].fd + k + 1]);
    }
  }
  if (ans == INF)
    printf("-1\n");
  else
    printf("%lld\n", ans);
  return 0;
}
