#include <bits/stdc++.h>
using namespace std;
struct tct {
  int d;
  int s, e;
  int c;
  tct(int d, int s, int e, int c) : d(d), s(s), e(e), c(c) {}
  tct() : d(0), s(0), e(0), c(0) {}
  bool operator<(const tct &other) const {
    if (d == other.d) return c < other.c;
    return d < other.d;
  }
};
long long ans1[1000006], ans2[1000006];
int ok1[1000006], ok2[1000006];
long long cur[100005];
tct arr[100005];
int n, m, d;
int main() {
  cin >> n >> m >> d;
  int i;
  for (i = 0; i < m; i++) {
    int a, b, c, d;
    cin >> a >> b >> c >> d;
    arr[i] = tct(a, b, c, d);
  }
  for (i = 1; i <= n; i++) cur[i] = (1LL << 40);
  sort(arr, arr + m);
  int cd = 1, und = n;
  for (i = 0; i < m; i++) {
    if (arr[i].e != 0) continue;
    while (cd < arr[i].d) {
      cd++;
      ans1[cd] = ans1[cd - 1];
      ok1[cd] = ok1[cd - 1];
    }
    if (arr[i].c < cur[arr[i].s]) {
      if (cur[arr[i].s] == (1LL << 40)) {
        und--;
        ans1[cd] += arr[i].c;
      } else
        ans1[cd] += (arr[i].c - cur[arr[i].s]);
      cur[arr[i].s] = arr[i].c;
    }
    ok1[cd] = (und == 0);
  }
  while (cd < 1000006) {
    cd++;
    ok1[cd] = ok1[cd - 1];
    ans1[cd] = ans1[cd - 1];
  }
  cd = 1000005;
  und = n;
  for (i = 1; i <= n; i++) cur[i] = (1LL << 40);
  for (i = m - 1; i >= 0; i--) {
    if (arr[i].s != 0) continue;
    while (cd > arr[i].d) {
      cd--;
      ans2[cd] = ans2[cd + 1];
      ok2[cd] = ok2[cd + 1];
    }
    if (arr[i].c < cur[arr[i].e]) {
      if (cur[arr[i].e] == (1LL << 40)) {
        und--;
        ans2[cd] += arr[i].c;
      } else
        ans2[cd] += (arr[i].c - cur[arr[i].e]);
      cur[arr[i].e] = arr[i].c;
    }
    ok2[cd] = (und == 0);
  }
  while (cd--) {
    ok2[cd] = ok2[cd + 1];
    ans2[cd] = ans2[cd + 1];
  }
  long long ans = (1LL << 60);
  for (i = 1; i < 1000005 - d; i++) {
    if (ok1[i] && ok2[i + d + 1]) ans = min(ans, ans1[i] + ans2[i + d + 1]);
  }
  cout << (ans == (1LL << 60) ? -1 : ans) << endl;
}
