#include <bits/stdc++.h>
using namespace std;
const int MAXN = 110000;
const long long INF = 1E12;
multiset<int> s[MAXN];
struct Flight1 {
  int d, p, c;
  Flight1(int _d, int _p, int _c) : d(_d), p(_p), c(_c) {}
  bool operator<(const Flight1& rhs) const { return d < rhs.d; }
};
struct Flight2 {
  int d, p;
  multiset<int>::iterator pos;
  Flight2(int _d, int _p, multiset<int>::iterator _pos)
      : d(_d), p(_p), pos(_pos) {}
  bool operator<(const Flight2& rhs) const { return d < rhs.d; }
};
vector<Flight1> A;
vector<Flight2> B;
long long c[MAXN], t[MAXN], sum = 0, ans = INF;
void update(int p) {
  long long tmp = t[p] + (s[p].empty() ? INF : *s[p].begin());
  sum += tmp - c[p], c[p] = tmp;
}
int main() {
  int n, m, k;
  scanf("%d%d%d", &n, &m, &k);
  for (int i = 1; i <= m; i++) {
    int d, f, t, c;
    scanf("%d%d%d%d", &d, &f, &t, &c);
    if (t == 0)
      A.push_back(Flight1(d, f, c));
    else
      B.push_back(Flight2(d, t, s[t].insert(c)));
  }
  sort(A.begin(), A.end());
  sort(B.begin(), B.end());
  for (int i = 1; i <= n; i++) t[i] = INF, update(i);
  for (int i = 0, j = 0; i < A.size(); i++) {
    vector<int> tmp;
    t[A[i].p] = min(t[A[i].p], 1ll * A[i].c);
    while (j < B.size() && B[j].d <= A[i].d + k)
      s[B[j].p].erase(B[j].pos), tmp.push_back(B[j++].p);
    update(A[i].p);
    for (int x : tmp) update(x);
    ans = min(ans, sum);
  }
  printf("%lld\n", ans < INF ? ans : -1);
  return 0;
}
