#include <bits/stdc++.h>
using namespace std;
const int N = 100100;
const int M = 1001000;
const int OO = 1e7;
const long long OOLL = 1e14;
int n, m, k;
multiset<int> st[N];
vector<pair<int, int>> a[M], b[M];
int pr[N];
long long sum;
int cnt;
bool u[N];
void add_from(int idx, int price) {
  cnt += !u[idx];
  u[idx] = true;
  sum -= pr[idx];
  pr[idx] = min(price, pr[idx]);
  sum += pr[idx];
}
void rmv(int idx, int val) {
  sum -= *st[idx].begin();
  --cnt;
  st[idx].erase(st[idx].find(val));
  if (st[idx].empty())
    sum = OOLL;
  else {
    ++cnt;
    sum += *st[idx].begin();
  }
}
int main() {
  scanf("%d%d%d", &n, &m, &k);
  ++n;
  for (int i = 1; i < n; ++i) {
    pr[i] = OO;
    sum += OO;
  }
  for (int i = 0; i < m; ++i) {
    int d, f, t, c;
    scanf("%d%d%d%d", &d, &f, &t, &c);
    if (f > 0)
      a[d].emplace_back(c, f);
    else {
      b[d].emplace_back(c, t);
      if (d > k) st[t].insert(c);
    }
  }
  bool f = true;
  for (int i = 1; i < n; ++i) {
    f &= !st[i].empty();
    if (!st[i].empty()) sum += *st[i].begin();
  }
  long long minSum = OOLL;
  for (int i = k + 1; i < M; ++i) {
    for (auto p : a[i - k]) add_from(p.second, p.first);
    for (auto p : b[i]) rmv(p.second, p.first);
    if (cnt == n - 1) minSum = min(minSum, sum);
  }
  if (minSum == OOLL) minSum = -1;
  if (f)
    printf("%lld\n", minSum);
  else
    puts("-1");
  return 0;
}
