#include <bits/stdc++.h>
using namespace std;
struct node {
  int d, f, t;
  long long c;
} pro[1000010];
long long fo[100010];
bool vis[100010];
long long sum1[1000010];
long long sum2[1000010];
bool cmp(node a, node b) { return a.d < b.d; }
int main() {
  int n, m, k;
  scanf("%d %d %d", &n, &m, &k);
  for (int i = 1; i <= m; i++)
    scanf("%d %d %d %lld", &pro[i].d, &pro[i].f, &pro[i].t, &pro[i].c);
  sort(pro + 1, pro + 1 + m, cmp);
  long long Sum = 0;
  int ans = 0, t = 1;
  for (int i = 1; i <= n; i++) fo[i] = 1000010, Sum += fo[i];
  memset(sum1, -1, sizeof(sum1));
  for (int i = 1; i <= 1000000; i++) {
    if (pro[t].d == i) {
      while (pro[t].d == i) {
        int v = pro[t].f;
        if (v != 0) {
          Sum -= fo[v];
          fo[v] = min(fo[v], pro[t].c);
          Sum += fo[v];
          if (!vis[v]) ans++;
          if (ans == n)
            sum1[i] = Sum;
          else
            sum1[i] = -1;
          vis[v] = true;
        } else
          sum1[i] = sum1[i - 1];
        t++;
      }
    } else
      sum1[i] = sum1[i - 1];
  }
  memset(vis, false, sizeof(vis));
  memset(sum2, -1, sizeof(sum2));
  ans = 0, t = m;
  Sum = 0;
  for (int i = 1; i <= n; i++) fo[i] = 1000010, Sum += fo[i];
  for (int i = 1000000; i >= 1; i--) {
    if (pro[t].d == i) {
      while (pro[t].d == i) {
        int v = pro[t].t;
        if (v != 0) {
          Sum -= fo[v];
          fo[v] = min(fo[v], pro[t].c);
          Sum += fo[v];
          if (!vis[v]) ans++;
          if (ans == n)
            sum2[i] = Sum;
          else
            sum2[i] = -1;
          vis[v] = true;
        } else
          sum2[i] = sum2[i + 1];
        t--;
      }
    } else
      sum2[i] = sum2[i + 1];
  }
  long long sum = 100000000000000;
  for (int i = 1; i <= 1000000 - k - 1; i++) {
    if (sum1[i] != -1 && sum2[i + k + 1] != -1) {
      sum = min(sum, sum1[i] + sum2[i + k + 1]);
    }
  }
  if (sum == 100000000000000)
    puts("-1");
  else
    printf("%lld\n", sum);
  return 0;
}
