#include <bits/stdc++.h>
using namespace std;
void func(void) {
  freopen("input.c", "r", stdin);
  freopen("output.c", "w", stdout);
}
void print(vector<long long> &v) {
  cout << v.size() << endl;
  for (int i = 0; i < v.size(); i++) {
    printf("%lld ", v[i]);
  }
  printf("\n");
}
void print(vector<pair<long long, long long> > &v) {
  cout << v.size() << endl;
  for (int i = 0; i < v.size(); i++) {
    printf("%lld %lld\n", v[i].first, v[i].second);
  }
}
void print(double d) { cout << fixed << setprecision(10) << d << endl; }
void print(string s, double d) {
  cout << s << " ";
  cout << fixed << setprecision(10) << d << endl;
}
const int N = 1e5 + 100;
struct info {
  long long day, cost, place;
  bool operator<(info k1) const { return day < k1.day; }
};
vector<info> in;
vector<info> out;
set<pair<long long, long long> > outFlight[N];
long long inFlight[N];
int main() {
  long long n, q, i, j = 0, temp, t, k, ans = 0, sum = 0, x, y, z, cnt = 0, m,
                     fg = 0, mx = 0, mx1 = 0, mn = 8e18,
                     mn1 = 8000000000000000000;
  scanf("%lld %lld %lld", &n, &m, &k);
  for (int i = 0; i < m; i++) {
    scanf("%lld %lld", &x, &y);
    scanf("%lld %lld", &z, &t);
    info xx;
    xx.day = x;
    xx.place = y;
    if (y == 0) xx.place = z;
    xx.cost = t;
    if (y)
      in.push_back(xx);
    else
      out.push_back(xx);
  }
  sort(in.begin(), in.end());
  sort(out.begin(), out.end());
  for (int i = 0; i < N; i++) inFlight[i] = 1e10;
  int ok = 0;
  for (int i = 0; i < out.size(); i++) {
    outFlight[out[i].place].insert({out[i].cost, i});
  }
  long long outSum = 0;
  long long inSum = 0;
  for (int i = 1; i <= n; i++) {
    if (outFlight[i].size() == 0) {
      printf("-1\n");
      return 0;
    }
    auto it = outFlight[i].begin();
    pair<long long, long long> p = *it;
    outSum += p.first;
  }
  cnt = 0;
  for (int i = 0; i < in.size(); i++) {
    long long now = in[i].day;
    long long place = in[i].place;
    long long cost = in[i].cost;
    if (inFlight[place] == 1e10) {
      inFlight[place] = cost;
      inSum += cost;
      cnt++;
    } else {
      inSum -= inFlight[place];
      inFlight[place] = min(inFlight[place], cost);
      inSum += inFlight[place];
    }
    now += k + 1;
    fg = 0;
    for (; ok < out.size(); ok++) {
      if (out[ok].day >= now) break;
      auto it = outFlight[out[ok].place].begin();
      pair<long long, long long> p = *it;
      outSum -= p.first;
      p = {out[ok].cost, ok};
      outFlight[out[ok].place].erase(p);
      if (outFlight[out[ok].place].size() == 0) {
        fg = 1;
        break;
      }
      it = outFlight[out[ok].place].begin();
      p = *it;
      outSum += p.first;
    }
    if (fg) break;
    if (cnt == n) {
      mn = min(mn, inSum + outSum);
    }
  }
  if (mn == 8e18) mn = -1;
  cout << mn << endl;
}
