#include <bits/stdc++.h>
using namespace std;
const int mod = 1e9 + 7;
int main() {
  ios::sync_with_stdio(0);
  cin.tie(0);
  int n, m, k;
  cin >> n >> m >> k;
  vector<long long> s1(1e6 + 2, 1LL * (1e12) * n),
      s2(1e6 + 2, 1LL * (1e12) * n), c1(n + 1, 1e12), c2(n + 1, 1e12);
  vector<pair<int, long long>> come, go;
  vector<pair<int, int>> p1, p2;
  for (int i = 0; i < m; i++) {
    int d, f, t, c;
    cin >> d >> f >> t >> c;
    if (f == 0) {
      p2.push_back(make_pair(d, go.size()));
      go.push_back(make_pair(t, c));
    } else {
      p1.push_back(make_pair(d, come.size()));
      come.push_back(make_pair(f, c));
    }
  }
  sort(p1.begin(), p1.end());
  sort(p2.begin(), p2.end());
  int d = 1e6;
  for (int i = p2.size() - 1; i >= 0; i--) {
    auto cc = go[p2[i].second];
    int dd = p2[i].first;
    while (d >= dd) s2[d] = s2[d + 1], d--;
    s2[dd] -= max(c2[cc.first] - cc.second, 0LL);
    c2[cc.first] = min(c2[cc.first], cc.second);
  }
  while (d > 0) s2[d] = s2[d + 1], d--;
  d++;
  k++;
  for (int i = 0; i < p1.size(); i++) {
    auto cc = come[p1[i].second];
    int dd = p1[i].first;
    while (d <= dd) s1[d] = s1[d - 1], d++;
    s1[dd] -= max(0LL, c1[cc.first] - cc.second);
    c1[cc.first] = min(c1[cc.first], cc.second);
  }
  while (d <= 1e6) s1[d] = s1[d - 1], d++;
  long long ans = 1e18;
  for (int i = 0; i + k < 1e6 + 1; i++) {
    if (s1[i] <= 1LL * 1e6 * n && s2[i] <= 1LL * 1e6 * n)
      ans = min(ans, s1[i] + s2[i + k]);
  }
  cout << (ans > 1e11 ? -1 : ans) << endl;
}
