#include <bits/stdc++.h>
using namespace std;
vector<pair<long long, long long> > G[1000006][2];
long long c1[1000006], c2[1000006];
long long now[100006];
signed main() {
  long long n, m, k;
  cin >> n >> m >> k;
  for (long long i = 0; i < m; i++) {
    long long d, f, t, c;
    cin >> d >> f >> t >> c;
    if (t == 0) {
      G[d][0].push_back(pair<long long, long long>(f, c));
    } else {
      G[d][1].push_back(pair<long long, long long>(t, c));
    }
  }
  for (long long i = 0; i < n + 1; i++) now[i] = 1e9;
  now[0] = n * 1e9;
  long long okn = 0;
  for (long long i = 0; i < 1000001; i++) {
    c1[i] = -1;
    for (auto e : G[i][0]) {
      if (now[e.first] > e.second) {
        if (now[e.first] == 1e9) okn++;
        now[0] -= now[e.first];
        now[e.first] = e.second;
        now[0] += now[e.first];
      }
    }
    if (okn == n) c1[i] = now[0];
  }
  okn = 0;
  for (long long i = 0; i < n + 1; i++) now[i] = 1e9;
  now[0] = n * 1e9;
  for (long long i = 1000000; i > 0; i--) {
    c2[i] = 1e15;
    for (auto e : G[i][1]) {
      if (now[e.first] > e.second) {
        if (now[e.first] == 1e9) okn++;
        now[0] -= now[e.first];
        now[e.first] = e.second;
        now[0] += now[e.first];
      }
    }
    if (okn == n) c2[i] = now[0];
  }
  for (long long i = 1000000; i > 0; i--) c2[i - 1] = min(c2[i], c2[i - 1]);
  long long ans = 1e16;
  for (long long i = 0; i < 1000000 - k; i++) {
    if (c1[i] == -1) continue;
    ans = min(ans, c1[i] + c2[i + k + 1]);
  }
  if (ans >= 1e15) ans = -1;
  cout << ans << endl;
}
