#include <bits/stdc++.h>
using namespace std;
int n, m, k, len, cnt1, cnt2;
long long f[2000009], mn[2000009];
struct node {
  int t, x, val;
} a[2000009], b[2000009];
bool cmp(node u, node v) { return u.t < v.t; }
int main() {
  scanf("%d%d%d", &n, &m, &k);
  int i, j, x, y, z, t;
  for (i = 1; i <= m; i++) {
    scanf("%d%d%d%d", &t, &x, &y, &z);
    if (x) {
      a[++cnt1] = (node){t, x, z};
    } else
      b[++cnt2] = (node){t, y, z};
  }
  sort(a + 1, a + cnt1 + 1, cmp);
  sort(b + 1, b + cnt2 + 1, cmp);
  long long inf = (long long)2000001 * n;
  long long now = inf * n;
  for (i = 1; i <= n; i++) mn[i] = inf;
  for (i = 1000000, j = cnt2; i; i--) {
    for (; j && b[j].t == i; j--) {
      now -= mn[b[j].x];
      ((mn[b[j].x] > (b[j].val)) ? mn[b[j].x] = (b[j].val) : 0);
      now += mn[b[j].x];
    }
    f[i] = now;
  }
  long long ans = inf * n;
  now = ans;
  for (i = 1; i <= n; i++) mn[i] = inf;
  for (i = j = 1; i + k + 1 <= 1000000; i++) {
    for (; j <= cnt1 && a[j].t == i; j++) {
      now -= mn[a[j].x];
      ((mn[a[j].x] > (a[j].val)) ? mn[a[j].x] = (a[j].val) : 0);
      now += mn[a[j].x];
    }
    ans = min(ans, now + f[i + k + 1]);
  }
  printf("%lld\n", (ans < inf) ? ans : -1);
  return 0;
}
