#include <bits/stdc++.h>
using namespace std;
struct node {
  int d, f, t, c;
} a[100010];
int n, m, k, c1[100010], c2[100010];
long long ans, ans1[100010], ans2[100010];
int find(int x, int l, int r) {
  int ret = -1, mid;
  while (l <= r) {
    mid = (l + r) >> 1;
    if (a[mid].d >= x)
      ret = mid, r = mid - 1;
    else
      l = mid + 1;
  }
  return ret;
}
int main() {
  ios::sync_with_stdio(false);
  int i, cnt = 0;
  cin >> n >> m >> k;
  for (i = 1; i <= m; i++) cin >> a[i].d >> a[i].f >> a[i].t >> a[i].c;
  for (i = 1; i <= n; i++) c1[i] = c2[i] = 1e7;
  ans = 10000000ll * n;
  sort(a + 1, a + m + 1, [&](node a, node b) { return a.d < b.d; });
  for (i = 1; i <= m && cnt < n; i++) {
    if (a[i].t == 0) {
      if (c1[a[i].f] == 1e7) cnt++;
      if (c1[a[i].f] > a[i].c) {
        ans -= c1[a[i].f] - a[i].c;
        c1[a[i].f] = a[i].c;
      }
    }
  }
  ans1[i - 1] = ans;
  for (; i <= m; i++) {
    if (c1[a[i].f] > a[i].c) {
      ans -= c1[a[i].f] - a[i].c;
      c1[a[i].f] = a[i].c;
    }
    ans1[i] = ans;
  }
  for (i = m, cnt = 0, ans = 10000000ll * n; i && cnt < n; i--) {
    if (a[i].f == 0) {
      if (c2[a[i].t] == 1e7) cnt++;
      if (c2[a[i].t] > a[i].c) {
        ans -= c2[a[i].t] - a[i].c;
        c2[a[i].t] = a[i].c;
      }
    }
  }
  ans2[i + 1] = ans;
  for (; i; i--) {
    if (c2[a[i].t] > a[i].c) {
      ans -= c2[a[i].t] - a[i].c;
      c2[a[i].t] = a[i].c;
    }
    ans2[i] = ans;
  }
  for (i = 1; !ans1[i]; i++)
    ;
  for (ans = 10000000ll * n; i <= m; i++) {
    int p = find(a[i].d + k + 1, i + 1, m);
    if (ans2[p]) ans = min(ans, ans1[i] + ans2[p]);
  }
  cout << (ans == 10000000ll * n ? -1 : ans);
  return 0;
}
