#include <bits/stdc++.h>
using namespace std;
const int maxn = 1000005;
struct node {
  int d, s, t;
  long long c;
} a[maxn];
long long x[maxn], y[maxn], cost[maxn];
int cmp(node a, node b) { return a.d < b.d; }
int main() {
  memset(cost, -1, sizeof(cost));
  int n, m, k;
  scanf("%d%d%d", &n, &m, &k);
  for (int i = 1; i <= m; i++) {
    scanf("%d%d%d%lld", &a[i].d, &a[i].s, &a[i].t, &a[i].c);
  }
  sort(a + 1, a + m + 1, cmp);
  int maxd = a[m].d, num = 0, now = 1;
  long long sum = 0;
  for (int i = 1; i <= maxd; i++) {
    while (a[now].d == i && now <= m) {
      if (a[now].s == 0) {
        now++;
        continue;
      }
      if (cost[a[now].s] == -1) {
        num++;
        cost[a[now].s] = a[now].c;
        sum += 1ll * a[now].c;
      } else if (cost[a[now].s] > a[now].c) {
        sum -= 1ll * (cost[a[now].s] - a[now].c);
        cost[a[now].s] = a[now].c;
      }
      now++;
    }
    if (num < n)
      x[i] = -1;
    else
      x[i] = sum;
  }
  memset(cost, -1, sizeof(cost));
  num = 0, now = m, sum = 0;
  for (int i = maxd; i >= 1; i--) {
    while (a[now].d == i && now > 0) {
      if (a[now].t == 0) {
        now--;
        continue;
      }
      if (cost[a[now].t] == -1) {
        num++;
        cost[a[now].t] = 1ll * a[now].c;
        sum += 1ll * a[now].c;
      } else if (cost[a[now].t] > a[now].c) {
        sum -= 1ll * (cost[a[now].t] - 1ll * a[now].c);
        cost[a[now].t] = a[now].c;
      }
      now--;
    }
    if (num < n)
      y[i] = -1;
    else
      y[i] = sum;
  }
  long long ans = -1;
  for (int i = 1; i <= maxd - k - 1; i++) {
    if (x[i] == -1 || y[i + k + 1] == -1) continue;
    if (ans == -1 || x[i] + y[i + k + 1] < ans) ans = x[i] + y[i + k + 1];
  }
  cout << ans;
  return 0;
}
