#include <bits/stdc++.h>
using namespace std;
const int N = 1000010;
int n, m, k;
long long ans = 1e12;
long long csaida[N];
vector<pair<long long, long long> > saida[N];
vector<pair<long long, pair<long long, long long> > > ord;
multiset<pair<long long, long long> > custo[N];
int main() {
  scanf("%d%d%d", &n, &m, &k);
  for (int(i) = (0); (i) < (m); (i)++) {
    int a, b, c, d;
    scanf("%d%d%d%d", &a, &b, &c, &d);
    if (b == 0) {
      saida[a].push_back(make_pair(d, c - 1));
    } else {
      ord.push_back(make_pair(a, make_pair(b - 1, d)));
      custo[b - 1].insert(make_pair(d, a));
    }
  }
  for (int(i) = (0); (i) < (n); (i)++) csaida[i] = 1e12;
  sort(ord.begin(), ord.end());
  reverse(ord.begin(), ord.end());
  long long ans = 1e18, res = 0;
  bool pode = true;
  for (int i = 0; i < n; i++) {
    if (custo[i].size() == 0)
      pode = false;
    else {
      res += (*custo[i].begin()).first;
    }
  }
  for (int i = 0; i < n; i++) res += csaida[i];
  int j = 0;
  for (int i = 1000000; i >= 0; i--) {
    if (!pode) break;
    for (int pi = 0; pi < saida[i].size(); pi++) {
      int v = saida[i][pi].second;
      if (csaida[v] > saida[i][pi].first) {
        res -= csaida[v] - saida[i][pi].first;
        csaida[v] = saida[i][pi].first;
      }
    }
    while (j < ord.size()) {
      if (!pode) break;
      if (ord[j].first > i - k - 1) {
        int v = ord[j].second.first, cus = ord[j].second.second,
            dia = ord[j].first;
        long long bst = (*custo[v].begin()).first;
        custo[v].erase(custo[v].find(make_pair(cus, dia)));
        if (custo[v].size() == 0) {
          pode = false;
          break;
        }
        long long nbst = (*custo[v].begin()).first;
        res += nbst - bst;
        j++;
      } else
        break;
    }
    if (!pode) break;
    ans = min(ans, res);
  }
  if (ans > 1e12)
    cout << -1 << endl;
  else
    cout << ans << endl;
}
