#include <bits/stdc++.h>
using namespace std;
const int M = 1e9 + 7;
const int N = 1e6 + 10;
vector<pair<pair<long long, long long>, long long> > a, b;
long long pre[N], nxt[N];
int prem[N], nxtm[N];
long long mask[N];
int main() {
  int n, m, K;
  scanf("%d%d%d", &n, &m, &K);
  for (int i = 0; i < m; i++) {
    int d, f, t, c;
    scanf("%d%d%d%d", &d, &f, &t, &c);
    if (f == 0) {
      b.emplace_back(make_pair(d, c), t);
    } else {
      a.emplace_back(make_pair(d, c), f);
    }
  }
  sort(a.begin(), a.end());
  int Size = 0;
  for (int i = 1; i <= 1000000; i++) {
    pre[i] = pre[i - 1];
    prem[i] = prem[i - 1];
    while (Size < a.size() && a[Size].first.first == i) {
      if (!mask[a[Size].second]) {
        mask[a[Size].second] = a[Size].first.second;
        pre[i] += a[Size].first.second;
        prem[i]++;
      } else if (mask[a[Size].second] > a[Size].first.second) {
        pre[i] += a[Size].first.second - mask[a[Size].second];
        mask[a[Size].second] = a[Size].first.second;
      }
      Size++;
    }
  }
  sort(b.begin(), b.end());
  Size = b.size() - 1;
  memset(mask, 0, sizeof mask);
  for (int i = 1000000; i >= 1; i--) {
    nxt[i] = nxt[i + 1];
    nxtm[i] = nxtm[i + 1];
    while (Size >= 0 && b[Size].first.first == i) {
      if (!mask[b[Size].second]) {
        nxt[i] += b[Size].first.second;
        mask[b[Size].second] = b[Size].first.second;
        nxtm[i]++;
      } else if (mask[b[Size].second] > b[Size].first.second) {
        nxt[i] += b[Size].first.second - mask[b[Size].second];
        mask[b[Size].second] = b[Size].first.second;
      }
      Size--;
    }
  }
  long long ans = 1LL << 60;
  for (int i = 1; i + K + 1 <= 1000000; i++) {
    if (prem[i] != n) continue;
    if (nxtm[i + K + 1] != n) break;
    ans = min(ans, pre[i] + nxt[i + K + 1]);
  }
  printf("%I64d\n", (ans == (1LL << 60)) ? -1 : ans);
  return 0;
}
