#include <bits/stdc++.h>
using namespace std;
const long long MOD = 1e9 + 7;
const long long N = 1e6 + 10;
vector<pair<long long, long long> > ans[N];
vector<pair<long long, long long> > ans1[N];
long long mp[100005];
long long check[100005];
long long check1[100005];
long long p1[N], p[N];
int32_t main() {
  long long n, m, k;
  cin >> n >> m >> k;
  for (long long i = 1; i <= m; i++) {
    long long x, y, z, z1;
    cin >> x >> y >> z >> z1;
    if (y != 0) {
      ans[x].push_back({y, z1});
    } else {
      ans1[x].push_back({z, z1});
    }
  }
  for (long long i = 1; i <= 1000000; i++) {
    p1[i] = -1;
    p[i] = -1;
  }
  long long ans2 = 0;
  long long cnt = 0;
  for (long long i = 1000000; i >= 1; i--) {
    for (auto it : ans1[i]) {
      long long k = it.first;
      if (mp[k] == 0) {
        check[k] = it.second;
        ans2 += it.second;
        mp[k] = 1;
        cnt++;
      } else {
        if (check[k] > it.second) {
          ans2 -= check[k];
          ans2 += it.second;
          check[k] = it.second;
        }
      }
    }
    if (cnt == n) {
      p[i] = ans2;
    }
  }
  for (long long i = 1; i <= n; i++) {
    mp[i] = 0;
  }
  ans2 = 0;
  cnt = 0;
  for (long long i = 1; i <= 1000000; i++) {
    for (auto it : ans[i]) {
      long long k = it.first;
      if (mp[k] == 0) {
        check1[k] = it.second;
        ans2 += it.second;
        mp[k] = 1;
        cnt++;
      } else {
        if (check1[k] > it.second) {
          ans2 -= check1[k];
          ans2 += it.second;
          check1[k] = it.second;
        }
      }
    }
    if (cnt == n) {
      p1[i] = ans2;
    }
  }
  long long mn = 1e15;
  for (long long i = 1; i <= 1000000; i++) {
    if (i + k + 1 <= 1000000) {
      if (p1[i] != -1 && p[i + k + 1] != -1) {
        mn = min(mn, p1[i] + p[i + k + 1]);
      }
    }
  }
  if (mn == 1e15) mn = -1;
  cout << mn << endl;
}
