#include <bits/stdc++.h>
using namespace std;
struct piii {
  int d, f, t, c;
  int i;
  friend int operator<(const piii &a, const piii &b) {
    if (a.d != b.d) return a.d < b.d;
    if (a.f != b.f) return a.f < b.f;
    if (a.t != b.t) return a.t < b.t;
    return a.c < b.c;
  }
} a[100008];
struct pii {
  int a;
  int i;
  friend int operator<(const pii &a, const pii &b) { return a.a < b.a; }
} ps[100008];
priority_queue<pii> quea;
int mina[100008];
int minb[100008];
vector<piii> veca[100008];
vector<piii> vecb[100008];
set<piii> setb;
int lastia[100008];
int lastib[100008];
int n, m, k;
long long ansa;
long long nowa;
int main(int argv, char *args[]) {
  scanf("%d%d%d", &n, &m, &k);
  for (int i = 0; i < m; i++) {
    scanf("%d", &a[i].d);
    scanf("%d", &a[i].f);
    scanf("%d", &a[i].t);
    scanf("%d", &a[i].c);
  }
  sort(a, a + m);
  for (int i = 1; i <= n; i++) {
    mina[i] = 1 << 30;
    minb[i] = 1 << 30;
    lastia[i] = -1;
    lastib[i] = -1;
  }
  for (int i = 0; i < m; i++) {
    if (a[i].f == 0) {
      continue;
    }
    a[i].c = min(a[i].c, mina[a[i].f]);
    mina[a[i].f] = a[i].c;
  }
  for (int i = m - 1; i >= 0; i--) {
    if (a[i].t == 0) {
      continue;
    }
    a[i].c = min(a[i].c, minb[a[i].t]);
    minb[a[i].t] = a[i].c;
  }
  for (int i = 0; i < m; i++) {
    if (a[i].f != 0) {
      veca[a[i].f].push_back(a[i]);
    } else {
      vecb[a[i].t].push_back(a[i]);
    }
  }
  for (int i = 1; i <= n; i++) {
    if (vecb[i].size()) {
      setb.insert(vecb[i][0]);
      lastib[i] = 0;
      nowa += vecb[i][0].c;
    } else {
      puts("-1");
      exit(0);
      ;
    }
  }
  ansa = 1ll << 62;
  int stpos = 0;
  for (int i = 1; i <= n; i++) {
    if (veca[i].size() == 0 || vecb[i].size() == 0) {
      puts("-1");
      exit(0);
      ;
    }
    stpos = max(stpos, veca[i][0].d);
    stpos = max(stpos, vecb[i][0].d - k - 1);
  }
  int cnta = 0;
  for (int i = 0; i < m; i++) {
    if (a[i].f != 0) {
      int st = a[i].d;
      if (lastia[a[i].f] == -1) {
        cnta++;
      } else {
        nowa -= a[lastia[a[i].f]].c;
      }
      nowa += a[i].c;
      lastia[a[i].f] = i;
      if (cnta == n && setb.size() == n) {
        while (1) {
          auto it = setb.begin();
          if (it->d - st - 1 < k) {
            lastib[it->t]++;
            if (lastib[it->t] >= vecb[it->t].size()) {
              goto outa;
            }
            nowa -= it->c;
            int tt = it->t;
            setb.erase(it);
            setb.insert(vecb[tt][lastib[tt]]);
            nowa += vecb[tt][lastib[tt]].c;
          } else {
            break;
          }
        }
        ansa = min(ansa, nowa);
      }
    } else {
      continue;
    }
  }
outa:
  0;
  if (ansa == (1ll << 62)) {
    puts("-1");
    exit(0);
    ;
  } else {
    printf("%I64d\n", ansa);
  }
  return 0;
}
