#include <bits/stdc++.h>
using namespace std;
const int mod = 1e9 + 7;
const long long inf = 3e18 + 5;
int add(int a, int b) { return (a += b) < mod ? a : a - mod; }
int mul(int a, int b) { return 1LL * a * b % mod; }
int sub(int a, int b) { return (a -= b) < 0 ? a + mod : a; }
int ctz(int x) { return __builtin_ctz(x); }
int clz(int x) { return __builtin_clz(x); }
vector<tuple<int, int, int>> g, tg;
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(0);
  int n, m, k;
  cin >> n >> m >> k;
  for (int i = 0; i < m; i++) {
    int d, u, v, w;
    cin >> d >> u >> v >> w;
    if (u == 0) {
      g.emplace_back(d, v, w);
    } else {
      tg.emplace_back(d, u, w);
    }
  }
  sort(g.begin(), g.end());
  sort(tg.begin(), tg.end());
  vector<int> mn(n + 1, mod);
  int N = int(g.size());
  long long cmn = 0;
  int cnt = 0;
  vector<pair<int, long long>> from;
  for (int i = N - 1; i >= 0; i--) {
    auto [x, y, z] = g[i];
    if (mn[y] > z) {
      if (mn[y] != mod)
        cmn -= mn[y];
      else
        cnt++;
      mn[y] = z;
      cmn += mn[y];
    }
    if (cnt == n) {
      from.emplace_back(x, cmn);
    }
  }
  sort(from.begin(), from.end());
  cnt = 0;
  cmn = 0;
  vector<int> mnn(n + 1, mod);
  N = int(tg.size());
  long long res = inf;
  for (int i = 0; i < N; i++) {
    auto [x, y, z] = tg[i];
    if (mnn[y] > z) {
      if (mnn[y] != mod)
        cmn -= mnn[y];
      else
        cnt++;
      mnn[y] = z;
      cmn += mnn[y];
    }
    if (cnt == n) {
      int ind =
          lower_bound(from.begin(), from.end(), make_pair(x + k + 1, 0ll)) -
          from.begin();
      if (ind == int(from.size())) continue;
      res = min(res, cmn + from[ind].second);
    }
  }
  cout << (res == inf ? -1 : res);
}
