#include <bits/stdc++.h>
using namespace std;
struct vec {
  long double x, y;
  bool operator==(const vec &a) const { return x == a.x && y == a.y; }
  bool operator<(const vec &a) const {
    if (a.x != x) return x < a.x;
    return y < a.y;
  }
  vec operator+(const vec &a) const { return {x + a.x, y + a.y}; }
  vec operator*(const long double &a) const { return {x * a, y * a}; }
  vec operator-(const vec &a) const { return {x - a.x, y - a.y}; }
  vec operator/(const long double &a) const { return {x / a, y / a}; }
  long double len() const { return sqrt(x * x + y * y); }
  long double dot(const vec &a) const { return x * a.x + y * a.y; }
  long double crs(const vec &a) const { return x * a.y - y * a.x; }
  vec proj(const vec &a) const {
    return (a / a.len()) * (*this).dot(a) / a.len();
  }
};
struct P {
  int x, y, z;
  bool operator<(const P &a) const { return x < a.x; }
};
bool as(P a, P b) { return a.x < b.x; }
long long x, y, z, mod = 998244353;
vector<P> v, v1;
int i, n, m, k, a, d, b, c;
int e;
long long o[311111];
long long l[2011111];
int j[111111];
stack<int> s;
priority_queue<P> q;
P u[1];
char r[1];
int main() {
  scanf("%d %d %d", &a, &b, &c);
  for (int t = 1; t <= b; t++) {
    scanf("%d %d %d %d", &n, &m, &d, &e);
    if (m == 0)
      v1.push_back({n, d, e});
    else
      v.push_back({n, m, e});
  }
  sort(v.begin(), v.end(), as);
  sort(v1.begin(), v1.end(), as);
  for (int t = 1; t <= a; x += o[t], t++) o[t] = 111111111111;
  for (int t = 1; t <= 2000001; t++) l[t] = x;
  for (int h = v1.size() - 1; h >= 0; h--) {
    x -= o[v1[h].y];
    x += min(o[v1[h].y], (long long)v1[h].z);
    l[v1[h].x] = x;
    o[v1[h].y] = min(o[v1[h].y], (long long)v1[h].z);
  }
  for (int t = 2000000; t > 0; t--) l[t] = min(l[t], l[t + 1]);
  x = 0;
  for (int t = 1; t <= a; x += o[t], t++) o[t] = 201111111111;
  y = z = x;
  for (int h = 0; h < v.size(); h++) {
    x -= o[v[h].y];
    x += min(o[v[h].y], (long long)v[h].z);
    o[v[h].y] = min(o[v[h].y], (long long)v[h].z);
    if (v[h].x + c + 1 <= 2000000) y = min(y, x + l[v[h].x + c + 1]);
  }
  if (y >= 111111111111)
    puts("-1");
  else
    printf("%lld", y);
}
