#include <bits/stdc++.h>
using namespace std;
long long costreach[1000050];
long long costaway[1000050];
int DAYY = 0;
struct Node {
  int d, f, t, c;
  void get() {
    cin >> d >> f >> t >> c;
    DAYY = max(DAYY, d + 1);
  }
};
Node node[1000050];
long long cur[1000050];
long long v = 0;
void solve() {
  int n, m, k;
  cin >> n >> m >> k;
  for (int i = 0; i < (int)(m); i++) {
    node[i].get();
  }
  for (int i = 0; i < (int)(n); i++) {
    cur[i + 1] = 1e13;
    v += cur[i + 1];
  }
  long long ans = 1e18;
  sort(node, node + m, [](Node a, Node b) { return a.d < b.d; });
  int day = 0;
  int i = 0;
  while (day <= DAYY) {
    while (i < m && node[i].d == day) {
      if (node[i].t == 0 && cur[node[i].f] > node[i].c) {
        v = v - cur[node[i].f] + node[i].c;
        cur[node[i].f] = node[i].c;
      }
      i++;
    }
    costreach[day] = v;
    day++;
  }
  reverse(node, node + m);
  v = 0;
  for (int i = 0; i < (int)(n); i++) {
    cur[i + 1] = 1e13;
    v += cur[i + 1];
  }
  day = DAYY;
  i = 0;
  while (day >= 0) {
    while (i < m && node[i].d == day) {
      if (node[i].t != 0 && cur[node[i].t] > node[i].c) {
        v = v - cur[node[i].t] + node[i].c;
        cur[node[i].t] = node[i].c;
      }
      i++;
    }
    costaway[day] = v;
    day--;
  }
  for (int d = 0; d <= DAYY; d++) {
    int g = d + k + 1;
    if (g > DAYY) break;
    long long v = costreach[d] + costaway[g];
    ans = min(ans, v);
  }
  if (ans > 1e12) {
    cout << "-1";
  } else {
    cout << ans;
  }
}
int main() {
  cin.tie(0);
  cout.tie(0);
  cin.sync_with_stdio(0);
  cout.sync_with_stdio(0);
  int TC = 1;
  for (int ZZ = 1; ZZ <= TC; ZZ++) {
    clock_t start = clock();
    solve();
    clock_t end = clock();
    cerr << "Time: " << (double)(end - start) / CLOCKS_PER_SEC << " seconds"
         << '\n';
  }
  return 0;
}
