#include <bits/stdc++.h>
using namespace std;
int n, m, k;
struct flight {
  int d, f, c;
  flight(int _d, int _f, int _c) {
    d = _d;
    f = _f;
    c = _c;
  }
};
vector<flight> a, b;
long long fa[100011], fb[100011];
int dau[100011];
bool cmp1(flight p, flight q) { return p.d < q.d; }
bool cmp2(flight p, flight q) { return p.d > q.d; }
void init(vector<flight>& x, long long f[]) {
  long long sum = 0;
  int cnt = 0;
  for (int i = 1; i <= n; i++) dau[i] = 0;
  for (int i = 0; i < x.size(); i++) f[i] = -1;
  for (int i = 0; i < x.size(); i++) {
    if (dau[x[i].f] == 0) {
      dau[x[i].f] = x[i].c;
      sum += x[i].c;
      cnt++;
    } else {
      if (dau[x[i].f] > x[i].c) {
        sum = sum - dau[x[i].f] + x[i].c;
        dau[x[i].f] = x[i].c;
      }
    }
    if (cnt == n) f[i] = sum;
  }
}
int main() {
  ios_base::sync_with_stdio(false);
  cin >> n >> m >> k;
  for (int i = 0; i < m; i++) {
    int d, f, t, c;
    cin >> d >> f >> t >> c;
    if (f == 0) b.push_back(flight(d, t, c));
    if (t == 0) a.push_back(flight(d, f, c));
  }
  sort(a.begin(), a.end(), cmp1);
  init(a, fa);
  sort(b.begin(), b.end(), cmp2);
  init(b, fb);
  int j = b.size() - 1;
  long long ans = -1;
  for (int i = 0; i < a.size(); i++) {
    if (fa[i] != -1) {
      while (j >= 0 && b[j].d <= a[i].d + k) j--;
      if (j < 0 || fb[j] == -1) break;
      if (ans == -1) {
        ans = fa[i] + fb[j];
      } else {
        ans = min(ans, fa[i] + fb[j]);
      }
    }
  }
  cout << ans;
}
