#include <bits/stdc++.h>
using namespace std;
long long val[112345], valf[112345];
struct node {
  int d, f, t, c;
  node() {}
  node(int d, int f, int t, int c) : d(d), f(f), t(t), c(c) {}
  void print() { printf("%d %d %d %d\n", d, f, t, c); }
} flightTo[112345], flightFrom[112345];
struct node2 {
  int t;
  long long s;
  node2() {}
  node2(int t, long long s) : t(t), s(s) {}
  bool operator<(const node2 &N) const {
    if (t == N.t) return s < N.s;
    return t < N.t;
  }
};
bool cmpto(node x, node y) { return x.d < y.d; }
bool cmpfrom(node x, node y) { return x.d > y.d; }
int main() {
  int n, m, k;
  scanf("%d%d%d", &n, &m, &k);
  int cntto = 0, cntfrom = 0;
  for (int i = 1; i <= m; i++) {
    int d, f, t, c;
    scanf("%d%d%d%d", &d, &f, &t, &c);
    if (t) {
      flightFrom[cntfrom++] = node(d, f, t, c);
    } else {
      flightTo[cntto++] = node(d, f, t, c);
    }
  }
  sort(flightTo, flightTo + cntto, cmpto);
  sort(flightFrom, flightFrom + cntfrom, cmpfrom);
  int cnt = 0;
  long long sum = 0;
  vector<node2> vto;
  for (int i = 0; i < cntto; i++) {
    node nt = flightTo[i];
    bool update = 0;
    if (val[nt.f] == 0) {
      cnt++;
      val[nt.f] = nt.c;
      sum += nt.c;
      update = 1;
    } else if (val[nt.f] > nt.c) {
      sum = sum - val[nt.f] + nt.c;
      val[nt.f] = nt.c;
      update = 1;
    }
    if (update && cnt == n) {
      vto.push_back(node2(nt.d, sum));
    }
  }
  int cntf = 0;
  long long sumf = 0;
  vector<node2> vfr;
  for (int i = 0; i < cntfrom; i++) {
    node nt = flightFrom[i];
    bool update = 0;
    if (valf[nt.t] == 0) {
      cntf++;
      valf[nt.t] = nt.c;
      sumf += nt.c;
      update = 1;
    } else if (valf[nt.t] > nt.c) {
      sumf = sumf - valf[nt.t] + nt.c;
      valf[nt.t] = nt.c;
      update = 1;
    }
    if (update && cntf == n) {
      vfr.push_back(node2(nt.d, sumf));
    }
  }
  sort(vfr.begin(), vfr.end());
  long long ans = -1;
  for (int i = 0; i < vto.size(); i++) {
    node2 nt = vto[i];
    auto it = lower_bound(vfr.begin(), vfr.end(), node2(nt.t + k + 1, -1));
    if (it == vfr.end()) continue;
    if (ans < 0)
      ans = vto[i].s + (*it).s;
    else
      ans = min(ans, vto[i].s + (*it).s);
  }
  printf("%I64d\n", ans);
  return 0;
}
