#include <bits/stdc++.h>
using namespace std;
const int sz = 1e6 + 9;
int n, m, k;
long long tr[sz], tr_sum, tr_cnt;
long long ret[sz], ret_sum, ret_cnt;
int d, first, t, c;
vector<pair<pair<int, int>, pair<int, int>>> v;
vector<pair<long long, long long>> home;
long long home_ans[sz];
long long ans = 1e18;
int days[sz];
int main() {
  cin >> n >> m >> k;
  for (int i = 0; i < m; ++i) {
    cin >> d >> first >> t >> c;
    v.push_back(make_pair(make_pair(d, first), make_pair(t, c)));
  }
  sort(v.begin(), v.end());
  for (int i = v.size() - 1; i >= 0; i--) {
    d = v[i].first.first;
    first = v[i].first.second;
    t = v[i].second.first;
    c = v[i].second.second;
    if (first) continue;
    if (!ret[t]) {
      ret[t] = c;
      ret_sum += c;
      ret_cnt++;
    } else if (ret[t] > c) {
      ret_sum -= ret[t];
      ret[t] = c;
      ret_sum += c;
    }
    if (ret_cnt == n) home.push_back(make_pair(d, ret_sum));
  }
  sort(home.begin(), home.end());
  int tmp = 0;
  for (auto u : home) days[tmp++] = u.first;
  for (int i = home.size() - 1; i >= 0; i--) {
    if (i == home.size() - 1)
      home_ans[i] = home[i].second;
    else
      home_ans[i] = min(home_ans[i + 1], home[i].second);
  }
  for (int i = 0; i < v.size(); ++i) {
    d = v[i].first.first;
    first = v[i].first.second;
    t = v[i].second.first;
    c = v[i].second.second;
    if (t) continue;
    if (!tr[first]) {
      tr[first] = c;
      tr_sum += c;
      tr_cnt++;
    } else if (tr[first] > c) {
      tr_sum -= tr[first];
      tr[first] = c;
      tr_sum += c;
    }
    if (tr_cnt == n) {
      int pos = lower_bound(days, days + home.size(), d + 1 + k) - days;
      if (pos >= home.size()) continue;
      ans = min(ans, tr_sum + home_ans[pos]);
    }
  }
  if (ans == 1e18)
    cout << -1;
  else
    cout << ans;
  return 0;
}
