#include <bits/stdc++.h>
using namespace std;
const int N = 1000 * 1000 + 5;
vector<pair<int, int>> from[N];
vector<pair<int, int>> to[N];
long long inf = 1e13;
long long best_from[N];
long long best_to[N];
long long cost[N];
int main() {
  int n, m, k;
  scanf("%d%d%d", &n, &m, &k);
  for (int i = 0; i < m; i++) {
    int d, f, t, c;
    scanf("%d%d%d%d", &d, &f, &t, &c);
    if (t == 0) {
      from[d].push_back({f, c});
    }
    if (f == 0) {
      to[d].push_back({t, c});
    }
  }
  long long sum = inf * n;
  for (int i = 1; i <= n; i++) {
    cost[i] = inf;
  }
  for (int i = 1; i < N; i++) {
    for (auto p : from[i]) {
      int x = p.first;
      int e = p.second;
      if (cost[x] > e) {
        sum -= cost[x] - e;
        cost[x] = e;
      }
    }
    best_from[i] = sum;
  }
  sum = inf * n;
  for (int i = 1; i <= n; i++) {
    cost[i] = inf;
  }
  for (int i = N - 1; i > 0; i--) {
    for (auto p : to[i]) {
      int x = p.first;
      int e = p.second;
      if (cost[x] > e) {
        sum -= cost[x] - e;
        cost[x] = e;
      }
    }
    best_to[i] = sum;
  }
  long long res = n * inf;
  for (int i = 1; i < N - k - 1; i++) {
    res = min(res, best_from[i] + best_to[i + k + 1]);
  }
  printf("%lld\n", res < inf ? res : -1);
}
