#include <bits/stdc++.h>
using namespace std;
const int N = 100000 + 10;
const int K = 1000000 + 10;
int n, m, k;
long long arr_cost_sum[K];
long long arr_cnt[K];
long long arr_cost[N];
bool arr[N];
long long dep_cost_sum[K];
long long dep_cnt[K];
long long dep_cost[N];
bool dep[N];
struct Flight {
  long long d, f, t, c;
};
vector<Flight> fs[2][K];
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(0);
  cin >> n >> m >> k;
  for (int i = 0; i < m; ++i) {
    Flight f;
    cin >> f.d >> f.f >> f.t >> f.c;
    if (f.f == 0)
      fs[0][f.d].push_back(f);
    else
      fs[1][f.d].push_back(f);
  }
  for (int i = 1; i < K; ++i) {
    arr_cnt[i] = arr_cnt[i - 1];
    arr_cost_sum[i] = arr_cost_sum[i - 1];
    for (auto& f : fs[1][i]) {
      if (!arr[f.f]) {
        arr[f.f] = 1;
        ++arr_cnt[i];
        arr_cost[f.f] = f.c;
        arr_cost_sum[i] += f.c;
      } else {
        if (f.c < arr_cost[f.f]) {
          arr_cost_sum[i] += (f.c - arr_cost[f.f]);
          arr_cost[f.f] = f.c;
        }
      }
    }
  }
  for (int i = K - 2; i >= 1; --i) {
    dep_cnt[i] = dep_cnt[i + 1];
    dep_cost_sum[i] = dep_cost_sum[i + 1];
    for (auto& f : fs[0][i]) {
      if (!dep[f.t]) {
        dep[f.t] = 1;
        ++dep_cnt[i];
        dep_cost[f.t] = f.c;
        dep_cost_sum[i] += f.c;
      } else {
        if (f.c < dep_cost[f.t]) {
          dep_cost_sum[i] += (f.c - dep_cost[f.t]);
          dep_cost[f.t] = f.c;
        }
      }
    }
  }
  set<pair<long long, long long>> dep_cost_day;
  for (int i = 1; i != K; ++i) {
    if (dep_cnt[i] != n) break;
    dep_cost_day.insert(pair<long long, long long>(dep_cost_sum[i], i));
  }
  long long res = -1;
  for (int i = 1; i <= k; ++i) {
    if (dep_cost_day.size() == 0) break;
    dep_cost_day.erase(pair<long long, long long>(dep_cost_sum[i], i));
  }
  for (int i = 1; i != K; ++i) {
    if (dep_cost_day.size() == 0) break;
    if (i + k <= K - 2)
      dep_cost_day.erase(
          pair<long long, long long>(dep_cost_sum[i + k], i + k));
    if (dep_cost_day.size() == 0) break;
    if (arr_cnt[i] != n) continue;
    long long cost = arr_cost_sum[i] + (dep_cost_day.begin()->first);
    if (res == -1)
      res = cost;
    else
      res = min(res, cost);
  }
  cout << res << endl;
  return 0;
}
