#include <bits/stdc++.h>
using namespace std;
const long long inf = (long long)1e18;
const int maxn = 100005, Maxd = 1000005;
int n, m, k;
vector<pair<int, int> > arrive[Maxd], leave[Maxd];
long long leaveCost[Maxd], Min[maxn];
int main() {
  scanf("%d%d%d", &n, &m, &k);
  int maxd = 0;
  for (int i = 0; i < m; i++) {
    int d, f, t, c;
    scanf("%d%d%d%d", &d, &f, &t, &c);
    if (t == 0)
      arrive[d].push_back(make_pair(f - 1, c));
    else
      leave[d].push_back(make_pair(t - 1, c));
    maxd = max(maxd, d);
  }
  long long cost = 0;
  int checkin = 0;
  for (int i = 0; i < n; i++) Min[i] = inf;
  for (int i = maxd; i >= 1; i--) {
    for (vector<pair<int, int> >::iterator j = leave[i].begin();
         j != leave[i].end(); ++j) {
      if (Min[j->first] == inf) {
        checkin++;
        Min[j->first] = j->second;
        cost += j->second;
      } else {
        if (Min[j->first] <= j->second) continue;
        cost -= Min[j->first] - j->second;
        Min[j->first] = j->second;
      }
    }
    if (checkin == n)
      leaveCost[i] = cost;
    else
      leaveCost[i] = inf;
  }
  cost = 0;
  checkin = 0;
  for (int i = 0; i < n; i++) Min[i] = inf;
  long long ans = inf;
  for (int i = 1; i <= maxd - k; i++) {
    if (checkin == n) ans = min(ans, cost + leaveCost[i + k]);
    for (vector<pair<int, int> >::iterator j = arrive[i].begin();
         j != arrive[i].end(); ++j) {
      if (Min[j->first] == inf) {
        checkin++;
        Min[j->first] = j->second;
        cost += j->second;
      } else {
        if (Min[j->first] <= j->second) continue;
        cost -= Min[j->first] - j->second;
        Min[j->first] = j->second;
      }
    }
  }
  if (ans != inf)
    cout << ans << endl;
  else
    cout << -1 << endl;
}
