#include <bits/stdc++.h>
using namespace std;
struct hi {
  int d, f, t, c;
};
const int N = 1e6;
const long long INF = 1e17;
int n, m, k;
hi a[N + 5];
void enter() {
  cin >> n >> m >> k;
  for (int i = (1), _b = (m); i <= _b; ++i)
    cin >> a[i].d >> a[i].f >> a[i].t >> a[i].c;
}
bool cmp(hi p, hi q) { return p.d < q.d; }
int cur[N + 5];
long long pre[N + 5], suf[N + 5];
void process() {
  for (int i = (0), _b = (N); i <= _b; ++i) cur[i] = -1;
  sort(a + 1, a + m + 1, cmp);
  long long sum = 0;
  int cnt = 0;
  for (int i = (0), _b = (N); i <= _b; ++i) pre[i] = suf[i] = INF;
  for (int i = (1), _b = (m); i <= _b; ++i)
    if (a[i].t == 0) {
      if (cur[a[i].f] == -1) {
        cur[a[i].f] = a[i].c;
        ++cnt;
        sum += a[i].c;
      } else if (cur[a[i].f] > a[i].c) {
        sum += -cur[a[i].f] + a[i].c;
        cur[a[i].f] = a[i].c;
      }
      if (cnt == n) pre[a[i].d] = sum;
    }
  for (int i = (0), _b = (N); i <= _b; ++i) cur[i] = -1;
  sum = 0;
  cnt = 0;
  for (int i = (m), _b = (1); i >= _b; --i)
    if (a[i].f == 0) {
      if (cur[a[i].t] == -1) {
        cur[a[i].t] = a[i].c;
        ++cnt;
        sum += a[i].c;
      } else if (cur[a[i].t] > a[i].c) {
        sum += -cur[a[i].t] + a[i].c;
        cur[a[i].t] = a[i].c;
      }
      if (cnt == n) suf[a[i].d] = sum;
    }
  for (int i = (1), _b = (N); i <= _b; ++i) pre[i] = min(pre[i - 1], pre[i]);
  for (int i = (N - 1), _b = (0); i >= _b; --i)
    suf[i] = min(suf[i + 1], suf[i]);
  long long ans = INF;
  for (int lb = (1), _b = (N - k); lb <= _b; ++lb) {
    ans = min(ans, pre[lb - 1] + suf[lb + k]);
  }
  if (ans >= INF) ans = -1;
  cout << ans;
}
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  enter();
  process();
  return 0;
}
