#include <bits/stdc++.h>
using namespace std;
long long int inf = 1e17;
long long int n, m, k, i, st, l = 0, ind, e = 0, d, c, j, f, r, bg = 0, lv = 0,
                              mini[100005], ans = inf;
vector<pair<long long int, pair<long long int, long long int> > > qu[1000005];
multiset<long long int> lea[100005];
multiset<long long int>::iterator it;
int main() {
  int tm, tt;
  cin >> n >> m >> k;
  for (i = 0; i <= n; i++) mini[i] = -1;
  for (i = 0; i < m; i++) {
    scanf("%I64d%I64d%I64d%I64d", &d, &st, &ind, &c);
    ind = max(ind, st);
    st = (st == 0);
    qu[d].push_back(make_pair(st, make_pair(ind, c)));
    if (st == 1) {
      if (lea[ind].size() == 0) {
        lv += c;
        e++;
      } else
        lv += min(c, *lea[ind].begin()) - *lea[ind].begin();
      lea[ind].insert(c);
    }
  }
  j = 0;
  f = 0;
  if (e < n) {
    cout << -1 << endl;
    return 0;
  }
  for (i = 0; i < 1000005 && !f; i++) {
    if (qu[i].size() == 0) continue;
    for (r = 0; r < qu[i].size(); r++) {
      ind = qu[i][r].second.first;
      c = qu[i][r].second.second;
      if (qu[i][r].first == 0) {
        if (mini[ind] == -1) {
          mini[ind] = c;
          l++;
          bg += c;
        } else {
          tm = mini[ind];
          mini[ind] = min(mini[ind], c);
          bg += mini[ind] - tm;
        }
      }
    }
    while (j < 1000001 && j <= i + k) {
      if (qu[j].size() == 0) {
        j++;
        continue;
      }
      for (r = 0; r < qu[j].size(); r++) {
        ind = qu[j][r].second.first;
        c = qu[j][r].second.second;
        if (qu[j][r].first == 1) {
          tm = *lea[ind].begin();
          it = lea[ind].find(c);
          lea[ind].erase(it);
          if (lea[ind].size() == 0) {
            f = 1;
            break;
          }
          tt = *lea[ind].begin();
          lv += (tt - tm);
        }
      }
      j++;
    }
    if (j <= i + k) break;
    if (l == n && !f) ans = min(ans, lv + bg);
  }
  if (ans == inf)
    cout << -1 << endl;
  else
    cout << ans << endl;
  return 0;
}
