3 2
1 0 1
1 2
2 3
 10 10
-1 -1 -1 -1 -1 -1 -1 -1 -1 -1
6 7
8 3
6 4
4 2
9 2
5 10
9 8
10 7
5 1
6 2

2
1
2
 0

#include <bits/stdc++.h>
using namespace std;
int ans, n, m, f1[1000005], vis[1000005], vis1[1000005], num, g1[1000005], k;
long long f[1000005], g[1000005];
struct he {
  int d, s, t, c;
} a[1000005];
bool cmp(he a, he b) { return a.d < b.d; }
int main() {
  scanf("%d%d%d", &n, &m, &k);
  for (int i = 1; i <= m; i++) {
    scanf("%d%d%d%d", &a[i].d, &a[i].s, &a[i].t, &a[i].c);
  }
  sort(a + 1, a + 1 + m, cmp);
  for (int i = 1; i <= m; i++) {
    f[i] = f[i - 1];
    if (a[i].t == 0) {
      if (!vis[a[i].s]) {
        vis[a[i].s] = a[i].c;
        num++;
        f[i] += (long long)a[i].c;
      } else {
        if (a[i].c < vis[a[i].s]) {
          f[i] = f[i] - (long long)vis[a[i].s] + (long long)a[i].c;
          vis[a[i].s] = a[i].c;
        }
      }
    }
    f1[i] = num;
  }
  num = 0;
  for (int i = m; i >= 1; i--) {
    g[i] = g[i + 1];
    if (a[i].s == 0) {
      if (!vis1[a[i].t]) {
        vis1[a[i].t] = a[i].c;
        num++;
        g[i] += a[i].c;
      } else {
        if (a[i].c < vis1[a[i].t]) {
          g[i] = g[i] - (long long)vis1[a[i].t] + (long long)a[i].c;
          vis1[a[i].t] = a[i].c;
        }
      }
    }
    g1[i] = num;
  }
  int pos1 = 1;
  int pos2 = m;
  while ((a[pos1].t != 0 || f1[pos1] != n) && pos1 <= m) pos1++;
  if (pos1 > m) {
    printf("-1\n");
    return 0;
  }
  while ((a[pos2].s != 0 || a[pos2].d - a[pos1].d > k || g1[pos2] != n) &&
         pos2 >= 0)
    pos2--;
  if (pos2 == 0) {
    printf("-1\n");
    return 0;
  }
  while ((a[pos2].d - a[pos1].d <= k || a[pos2].s != 0) && pos2 <= m) pos2++;
  if (g1[pos2] != n || pos2 > m) {
    printf("-1\n");
    return 0;
  }
  pos1 = pos2;
  while (pos1 >= 1 && (a[pos1].t != 0 || a[pos2].d - a[pos1].d <= k)) pos1--;
  long long ans = (long long)1e16;
  while (pos2 <= m && pos1 <= m) {
    ans = min(ans, f[pos1] + g[pos2]);
    pos1++;
    while ((a[pos1].t != 0 || f1[pos1] != n) && pos1 <= m) pos1++;
    while ((a[pos2].s != 0 || a[pos2].d - a[pos1].d <= k || g1[pos2] != n) &&
           pos2 <= m)
      pos2++;
  }
  printf("%I64d\n", ans);
}
