#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using pii = pair<int, int>;
using pll = pair<ll, ll>;
using pil = pair<int, ll>;
using pli = pair<ll, int>;
using piii = pair<int, pii>;
using plll = pair<ll, pll>;
using pib = pair<int, bool>;
using pdi = pair<double, int>;
using pid = pair<int, double>;
using ld = long double;
using piiii = pair<pii, pii>;
bool cmp(piiii &p1, piiii &p2) {
  if (p1.first.first == p2.first.first) {
    return p1.second.second < p2.second.second;
  }
  return p1.first.first < p2.first.first;
}
int n, m, k, a, b, c, d, cost[100001];
bool v[100001];
vector<piiii> v1, v2;
stack<piiii> stk[100001];
int main() {
  ios::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  cin >> n >> m >> k;
  for (int i = 0; i < m; i++) {
    cin >> a >> b >> c >> d;
    if (b == 0) {
      v2.push_back({{a, b}, {c, d}});
    } else {
      v1.push_back({{a, b}, {c, d}});
    }
  }
  sort(v1.begin(), v1.end());
  sort(v2.begin(), v2.end());
  ll t1 = 0;
  int cnt = 0;
  ll t2 = 0;
  for (int i = v2.size() - 1; i >= 0; i--) {
    if (stk[v2[i].second.first].empty()) t2++;
    if (stk[v2[i].second.first].empty() ||
        v2[i].second.second < stk[v2[i].second.first].top().second.second)
      stk[v2[i].second.first].push(v2[i]);
    else
      v[i] = true;
  }
  if (t2 != n) {
    cout << -1 << "\n";
    return 0;
  }
  t2 = 0;
  for (int i = 1; i <= n; i++) {
    t2 += stk[i].top().second.second;
  }
  ll ans = 0x3f3f3f3f3f;
  bool first = true;
  int idx = 0;
  for (int i = 0; i < v1.size(); i++) {
    if (cost[v1[i].first.second] == 0) cnt++;
    if (cost[v1[i].first.second] == 0 ||
        cost[v1[i].first.second] > v1[i].second.second) {
      t1 += v1[i].second.second - cost[v1[i].first.second];
      cost[v1[i].first.second] = v1[i].second.second;
    } else
      continue;
    while (v2[idx].first.first - v1[i].first.first <= k) {
      if (v[idx]) {
        idx++;
        continue;
      }
      if (stk[v2[idx].second.first].size() == 1) {
        first = false;
        break;
      }
      piiii p = stk[v2[idx].second.first].top();
      stk[v2[idx].second.first].pop();
      t2 -= p.second.second - stk[v2[idx].second.first].top().second.second;
      idx++;
    }
    if (!first) break;
    if (cnt == n) {
      ans = min(ans, t1 + t2);
    }
  }
  if (ans == 0x3f3f3f3f3f) {
    cout << -1 << "\n";
  } else {
    cout << ans << "\n";
  }
  return 0;
}
