#include <bits/stdc++.h>
using namespace std;
const int N = 1e6 + 5;
const long long inf = 1e12;
int n, m, k;
vector<pair<int, int> > a[N], b[N];
long long mn1[N], mn2[N];
long long an1[N], an2[N];
int main() {
  cin >> 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 (f == 0) {
      b[d].push_back({t - 1, c});
    } else {
      a[d].push_back({f - 1, c});
    }
  }
  for (int i = 0; i < N; ++i) {
    an1[i] = an2[i] = 1e18;
    mn1[i] = mn2[i] = inf;
  }
  int cnt = 0;
  long long cur_sum = 0;
  for (int i = 0; i < N; ++i) {
    for (auto it : a[i]) {
      int cost = it.second;
      int town = it.first;
      if (mn1[town] == inf) {
        cnt++;
        cur_sum += cost;
        mn1[town] = cost;
      } else if (mn1[town] > cost) {
        cur_sum -= mn1[town] - cost;
        mn1[town] = cost;
      }
    }
    if (cnt == n) {
      an1[i] = cur_sum;
    }
  }
  cnt = 0;
  cur_sum = 0;
  for (int i = N - 1; i >= 0; --i) {
    for (auto it : b[i]) {
      int cost = it.second;
      int town = it.first;
      if (mn2[town] == inf) {
        cnt++;
        cur_sum += cost;
        mn2[town] = cost;
      } else if (mn2[town] > cost) {
        cur_sum -= mn2[town] - cost;
        mn2[town] = cost;
      }
    }
    if (cnt == n) {
      an2[i] = cur_sum;
    }
  }
  long long ans = 1e18;
  for (int i = 0; i + k + 1 < N; ++i) {
    ans = min(ans, an1[i] + an2[i + k + 1]);
  }
  if (ans == 1e18) ans = -1;
  cout << ans << endl;
  return 0;
}
