#include <bits/stdc++.h>
using namespace std;
const double pi = 3.141592653589793;
long long inf = 1000000000000000LL;
int flag[21111111];
vector<pair<long long, long long> > vec[1111111], vecc[1111111];
long long f[2111111];
long long s[2111111];
long long low[2111111];
int main() {
  ios::sync_with_stdio(false);
  cin.tie(0);
  long long n, m, k;
  long long a, x, y, c;
  cin >> n >> m >> k;
  for (int i = 0; i < m; i++) {
    cin >> a >> x >> y >> c;
    if (x == 0) {
      vecc[a].push_back(make_pair(y, c));
    } else
      vec[a].push_back(make_pair(x, c));
  }
  c = 0;
  int ind = 0;
  memset(flag, 0, sizeof flag);
  long long cost = 0;
  int d1 = -1, d2 = -1;
  for (int i = 0; i <= n; i++) low[i] = inf;
  for (int i = 1; i <= 1000000; i++) {
    s[i] = inf;
    for (pair<long long, long long> x : vec[i]) {
      long long ct = x.first, cs = x.second;
      if (flag[ct] == 0) {
        flag[ct] = 1;
        cost += cs;
        low[ct] = cs;
        c++;
      } else if (low[ct] > cs) {
        cost -= low[ct];
        low[ct] = cs;
        cost += cs;
      }
    }
    if (c == n) {
      s[i] = min(s[i], cost);
    }
  }
  c = 0;
  ind = m - 1;
  memset(flag, 0, sizeof flag);
  cost = 0;
  for (int i = 0; i <= n; i++) low[i] = inf;
  for (int i = 1000000; i >= 1; i--) {
    f[i] = inf;
    for (pair<long long, long long> x : vecc[i]) {
      long long ct = x.first, cs = x.second;
      if (flag[ct] == 0) {
        flag[ct] = 1;
        cost += cs;
        low[ct] = cs;
        c++;
      } else if (low[ct] > cs) {
        cost -= low[ct];
        low[ct] = cs;
        cost += cs;
      }
    }
    if (c == n) {
      f[i] = min(f[i], cost);
    }
  }
  long long ans = inf;
  for (int i = 1; i <= 1000000; i++) {
    if (i + k + 1 <= 1000000) {
      ans = min(ans, s[i] + f[i + k + 1]);
    }
  }
  if (ans >= inf || ans <= 0) {
    cout << "-1" << endl;
  } else {
    cout << ans << endl;
  }
  return 0;
}
