#include <bits/stdc++.h>
using namespace std;
vector<pair<long long, long long>> in[1000010], out[1000010];
long long inc[1000010], outc[1000010], was[100010];
int32_t main() {
  ios_base::sync_with_stdio(false);
  cin.tie(0);
  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) in[d].push_back({c, f});
    if (f == 0) out[d].push_back({c, t});
  }
  for (long long i = 0; i < 1000005; i++) inc[i] = outc[i] = 1e18;
  for (long long i = 0; i < 100005; i++) was[i] = 1e18;
  long long visit = 0;
  long long cost = 0;
  for (long long i = 0; i < 1000005; i++) {
    for (auto j : in[i]) {
      if (was[j.second] == 1e18) {
        visit++;
        cost += j.first;
        was[j.second] = j.first;
      } else if (was[j.second] > j.first) {
        cost += j.first - was[j.second];
        was[j.second] = j.first;
      }
    }
    if (visit == n) inc[i] = cost;
  }
  for (long long i = 0; i < 100005; i++) was[i] = 1e18;
  visit = 0, cost = 0;
  for (long long i = 1000005; i >= 0; i--) {
    for (auto j : out[i]) {
      if (was[j.second] == 1e18) {
        visit++;
        cost += j.first;
        was[j.second] = j.first;
      } else if (was[j.second] > j.first) {
        cost += j.first - was[j.second];
        was[j.second] = j.first;
      }
    }
    if (visit == n) outc[i] = cost;
  }
  long long ans = 1e18;
  for (long long i = 0; i + k < 1000001; i++) {
    ans = min(ans, inc[i] + outc[i + k + 1]);
  }
  if (ans == 1e18)
    cout << "-1\n";
  else
    cout << ans << "\n";
  return 0;
}
