#include <bits/stdc++.h>
using namespace std;
const int max_days = 1e6;
const long long inf = 1e12;
struct Flight {
  int day, from, to;
  long long cost;
};
Flight flights[100100];
long long min_cost_to[100100];
long long min_cost_from[100100];
long long prefix_cost[max_days + 1];
long long suffix_cost[max_days + 1];
int main() {
  ios::sync_with_stdio(false);
  cin.tie(nullptr);
  cout.tie(nullptr);
  int n, m, k;
  cin >> n >> m >> k;
  for (int i = 0; i < m; i++)
    cin >> flights[i].day >> flights[i].from >> flights[i].to >>
        flights[i].cost;
  sort(flights, flights + m,
       [](Flight& lhs, Flight& rhs) { return lhs.day < rhs.day; });
  for (int i = 0; i <= n; i++) min_cost_to[i] = min_cost_from[i] = inf;
  long long total_cost = n * inf;
  for (int i = 0; i <= max_days; i++)
    prefix_cost[i] = suffix_cost[i] = total_cost;
  for (int i = 0; i < m; i++)
    if (flights[i].to == 0) {
      if (flights[i].cost < min_cost_to[flights[i].from]) {
        total_cost -= min_cost_to[flights[i].from] - flights[i].cost;
        min_cost_to[flights[i].from] = flights[i].cost;
      }
      prefix_cost[flights[i].day] = total_cost;
    }
  for (int i = 1; i <= max_days; i++)
    prefix_cost[i] = min(prefix_cost[i], prefix_cost[i - 1]);
  total_cost = n * inf;
  for (int i = m - 1; i >= 0; i--)
    if (flights[i].from == 0) {
      if (flights[i].cost < min_cost_from[flights[i].to]) {
        total_cost -= min_cost_from[flights[i].to] - flights[i].cost;
        min_cost_from[flights[i].to] = flights[i].cost;
      }
      suffix_cost[flights[i].day] = total_cost;
    }
  for (int i = max_days - 1; i >= 1; i--)
    suffix_cost[i] = min(suffix_cost[i], suffix_cost[i + 1]);
  long long ans = n * inf;
  for (int i = 1; i + k + 1 <= max_days; i++)
    ans = min(ans, prefix_cost[i] + suffix_cost[i + k + 1]);
  cout << (ans < inf ? ans : -1);
}
