#include <bits/stdc++.h>
using namespace std;
struct node {
  int d, f, t;
  long long c;
} a[100005];
int cmp(node a, node b) { return a.d < b.d; }
long long INF = 0x3f3f3f3f3f3f;
long long cost[100005];
int vis[100005];
int cnt1[1000006];
int cnt2[1000006];
long long sum2[1000006];
long long sum1[1000006];
int main() {
  int n, m, k;
  memset(cnt1, 0, sizeof(cnt1));
  memset(cnt2, 0, sizeof(cnt2));
  memset(vis, 0, sizeof(vis));
  memset(cost, INF, sizeof(cost));
  memset(sum1, 0, sizeof(sum1));
  memset(sum2, 0, sizeof(sum2));
  scanf("%d%d%d", &n, &m, &k);
  for (int i = 1; i <= m; i++) {
    scanf("%d%d%d%I64d", &a[i].d, &a[i].f, &a[i].t, &a[i].c);
  }
  sort(a + 1, a + 1 + m, cmp);
  int pre = 0;
  for (int i = 1; i <= m; i++) {
    if (a[i].f == 0) continue;
    int f = a[i].f;
    int d = a[i].d;
    sum1[d] = sum1[pre];
    cnt1[d] = cnt1[pre];
    if (cost[f] > a[i].c) {
      if (vis[f] == 1)
        sum1[d] = sum1[d] - cost[f] + a[i].c;
      else
        sum1[d] += a[i].c;
      cost[f] = a[i].c;
      if (vis[f] == 0) {
        cnt1[d]++;
        vis[f] = 1;
      }
    }
    pre = d;
  }
  for (int i = 1; i <= 1000000; i++) {
    if (cnt1[i] == 0) cnt1[i] = cnt1[i - 1];
    if (sum1[i] == 0) sum1[i] = sum1[i - 1];
  }
  memset(vis, 0, sizeof(vis));
  pre = 1000000;
  memset(cost, INF, sizeof(cost));
  for (int i = m; i >= 1; i--) {
    if (a[i].t == 0) continue;
    int d = a[i].d;
    int t = a[i].t;
    sum2[d] = sum2[pre];
    cnt2[d] = cnt2[pre];
    if (cost[t] > a[i].c) {
      if (vis[t] == 1)
        sum2[d] = sum2[d] - cost[t] + a[i].c;
      else
        sum2[d] += a[i].c;
      cost[t] = a[i].c;
      if (vis[t] == 0) {
        cnt2[d]++;
        vis[t] = 1;
      }
    }
    pre = d;
  }
  for (int i = 1000000; i >= 0; i--) {
    if (cnt2[i] == 0) cnt2[i] = cnt2[i + 1];
    if (sum2[i] == 0) sum2[i] = sum2[i + 1];
  }
  long long ans = INF;
  for (int i = 1; i <= 1000000; i++) {
    if (i + k + 1 > 1000000) break;
    if (cnt1[i] == n && cnt2[i + k + 1] == n)
      ans = min(ans, (long long)sum1[i] + sum2[i + k + 1]);
  }
  if (ans == INF) {
    printf("-1\n");
    return 0;
  }
  printf("%I64d\n", ans);
  return 0;
}
