#include <bits/stdc++.h>
using namespace std;
const int maxd = 2000036;
const int64_t inf = 1000000000000000018;
int32_t main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  int n, m, k;
  cin >> n >> m >> k;
  vector<vector<pair<pair<int, int>, int64_t> > > edges(maxd);
  for (int i = 0; i < m; ++i) {
    pair<int, pair<pair<int, int>, int64_t> > e;
    cin >> e.first >> e.second.first.first >> e.second.first.second >>
        e.second.second;
    edges[e.first].push_back(e.second);
  }
  vector<int64_t> pref_days(maxd, inf), suff_days(maxd, inf);
  int64_t hence = 0;
  set<int> reachable;
  vector<int64_t> c_min(n + 1, inf);
  for (int d = maxd - 1; d >= 0; --d) {
    for (pair<pair<int, int>, int64_t> e : edges[d]) {
      if (e.first.second) {
        reachable.insert(e.first.second);
        if (c_min[e.first.second] > e.second) {
          if (c_min[e.first.second] != inf) hence -= c_min[e.first.second];
          c_min[e.first.second] = e.second;
          hence += c_min[e.first.second];
        }
      }
    }
    if (int(reachable.size()) == n) suff_days[d] = hence;
  }
  hence = 0;
  reachable.clear();
  c_min.assign(n + 1, inf);
  int64_t ans = inf;
  for (int d = 1; d <= maxd / 2; ++d) {
    for (pair<pair<int, int>, int64_t> e : edges[d]) {
      if (e.first.first) {
        reachable.insert(e.first.first);
        if (c_min[e.first.first] > e.second) {
          if (c_min[e.first.first] != inf) hence -= c_min[e.first.first];
          c_min[e.first.first] = e.second;
          hence += c_min[e.first.first];
        }
      }
    }
    if (int(reachable.size()) == n) pref_days[d] = hence;
    ans = min(ans, pref_days[d] + suff_days[d + k + 1]);
  }
  if (ans == inf) ans = -1;
  cout << ans << '\n';
}
