#include <bits/stdc++.h>
const long long int MAX = 1e12;
using namespace std;
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  cout.tie(NULL);
  int n, m, k;
  cin >> n >> m >> k;
  vector<array<long long int, 4>> v;
  for (int i = 0; i < m; i++) {
    long long int d, p, f, t;
    cin >> d >> f >> t >> p;
    long long int b = 0;
    if (f == 0) {
      b = 1;
    }
    v.push_back({d, f + t, b, p});
  }
  sort(v.begin(), v.end());
  vector<long long int> v1(n + 1, MAX);
  long long int s = MAX * n;
  stack<pair<long long int, long long int>> st;
  st.push({s, MAX});
  for (int i = m - 1; i >= 0; i--) {
    long long int d, c, b, p;
    d = v[i][0], c = v[i][1], b = v[i][2], p = v[i][3];
    if (b) {
      if (p < v1[c]) {
        s -= v1[c];
        v1[c] = p;
        s += p;
        st.push({d, s});
      }
    }
  }
  v1.clear();
  v1.resize(n + 1, MAX);
  s = MAX * n;
  long long int ans = INT64_MAX;
  for (int i = 0; i < m; i++) {
    long long int d, c, b, p;
    d = v[i][0], c = v[i][1], b = v[i][2], p = v[i][3];
    if (!b) {
      if (p < v1[c]) {
        s -= v1[c];
        v1[c] = p;
        s += p;
        while (st.top().first < d + k + 1) {
          st.pop();
        }
        ans = min(ans, st.top().second + s);
      }
    }
  }
  if (ans >= MAX) {
    cout << "-1\n";
  } else {
    cout << ans << '\n';
  }
  return 0;
}
