#include <bits/stdc++.h>
using namespace std;
template <class T1>
void deb(T1 e1) {
  cout << e1 << endl;
}
template <class T1, class T2>
void deb(T1 e1, T2 e2) {
  cout << e1 << " " << e2 << endl;
}
template <class T1, class T2, class T3>
void deb(T1 e1, T2 e2, T3 e3) {
  cout << e1 << " " << e2 << " " << e3 << endl;
}
template <class T1, class T2, class T3, class T4>
void deb(T1 e1, T2 e2, T3 e3, T4 e4) {
  cout << e1 << " " << e2 << " " << e3 << " " << e4 << endl;
}
template <class T1, class T2, class T3, class T4, class T5>
void deb(T1 e1, T2 e2, T3 e3, T4 e4, T5 e5) {
  cout << e1 << " " << e2 << " " << e3 << " " << e4 << " " << e5 << endl;
}
template <class T1, class T2, class T3, class T4, class T5, class T6>
void deb(T1 e1, T2 e2, T3 e3, T4 e4, T5 e5, T6 e6) {
  cout << e1 << " " << e2 << " " << e3 << " " << e4 << " " << e5 << " " << e6
       << endl;
}
const long long int mod = 10000000000007;
vector<pair<long long int, long long int> > adj1[1000005];
vector<pair<long long int, long long int> > adj2[1000005];
long long int come[1000005];
long long int bak[1000005];
long long int pre[1000005];
int main() {
  int n, m, k;
  scanf("%d %d %d", &n, &m, &k);
  for (int i = 1; i <= m; i++) {
    long long int u, v, d, c;
    scanf("%lld %lld %lld %lld", &d, &u, &v, &c);
    if (u == 0) {
      adj2[d].push_back(make_pair(v, c));
    } else {
      adj1[d].push_back(make_pair(u, c));
    }
  }
  for (int i = 1; i <= n; i++) {
    pre[i] = mod;
    come[0] += pre[i];
  }
  for (int i = 1; i < 1000005; i++) {
    long long int now = come[i - 1];
    for (int j = 0; j < adj1[i].size(); j++) {
      int u = adj1[i][j].first;
      long long int cost = adj1[i][j].second;
      if (pre[u] > cost) {
        now -= pre[u];
        pre[u] = cost;
        now += pre[u];
      }
    }
    come[i] = now;
  }
  for (int i = 1; i <= n; i++) {
    pre[i] = mod;
    bak[1000005 - 1] += pre[i];
  }
  for (int i = 1000005 - 2; i >= 1; i--) {
    long long int now = bak[i + 1];
    for (int j = 0; j < adj2[i].size(); j++) {
      int u = adj2[i][j].first;
      long long int cost = adj2[i][j].second;
      if (pre[u] > cost) {
        now -= pre[u];
        pre[u] = cost;
        now += pre[u];
      }
    }
    bak[i] = now;
  }
  long long int ans = mod * 100;
  for (int i = 1; i + k < 1000005; i++) {
    ans = min(ans, come[i - 1] + bak[i + k]);
  }
  if (ans >= mod) ans = -1;
  printf("%lld\n", ans);
  return 0;
}
