#include <bits/stdc++.h>
using namespace std;
const int N = 1e6 + 5;
const int INF = 0x3f3f3f3f;
const long long llINF = 0x3f3f3f3f3f3f3f3f;
const int mod = 998244353;
void read(int &ans) {
  long long x = 0, w = 1;
  char ch = 0;
  while (!isdigit(ch)) {
    if (ch == '-') w = -1;
    ch = getchar();
  }
  while (isdigit(ch)) {
    x = x * 10 + (ch - '0');
    ch = getchar();
  }
  ans = x * w;
}
int v[N];
long long mi[N];
long long ma[N];
set<int> se;
struct node {
  int d, f, t, c;
} a[N];
bool cmp(node x, node y) { return x.d < y.d; }
int main() {
  memset((mi), (INF), sizeof(mi));
  memset((ma), (INF), sizeof(ma));
  long long ans = mi[0];
  long long ans1 = mi[0];
  int n, m, k, d, f, t, c;
  int s1, e1, s2, e2;
  s1 = e1 = s2 = e2 = 0;
  int flag = 0;
  read(n), read(m), read(k);
  for (int i = 0; i < m; ++i) {
    read(d), read(f), read(t), read(c);
    a[i] = {d, f, t, c};
    flag = max(flag, d);
  }
  sort(a, a + m, cmp);
  long long sum = 0;
  for (int i = 0; i < m; ++i) {
    if (a[i].f == 0) continue;
    if (se.size() && se.find(a[i].f) != se.end()) {
      if (v[a[i].f] > a[i].c) {
        sum = sum - v[a[i].f] + a[i].c;
        v[a[i].f] = a[i].c;
      }
    } else {
      se.insert(a[i].f);
      v[a[i].f] = a[i].c;
      sum += a[i].c;
    }
    if (se.size() == n) {
      if (s1 == 0)
        e1 = s1 = a[i].d;
      else
        e1 = a[i].d;
      mi[a[i].d] = min(mi[a[i].d], sum);
    }
  }
  se.clear();
  sum = 0;
  for (int i = m - 1; i >= 0; --i) {
    if (a[i].t == 0) continue;
    if (se.size() && se.find(a[i].t) != se.end()) {
      if (v[a[i].t] > a[i].c) {
        sum = sum - v[a[i].t] + a[i].c;
        v[a[i].t] = a[i].c;
      }
    } else {
      se.insert(a[i].t);
      v[a[i].t] = a[i].c;
      sum += a[i].c;
    }
    if (se.size() == n) {
      if (e2 == 0)
        s2 = e2 = a[i].d;
      else
        s2 = a[i].d;
      ma[a[i].d] = min(ma[a[i].d], sum);
    }
  }
  for (int i = e1; i <= flag; ++i) mi[i] = mi[e1];
  for (int i = 1; i <= s2; ++i) ma[i] = ma[s2];
  for (int i = s1 + 1; i <= e1; ++i) {
    if (mi[i] > mi[i - 1]) mi[i] = mi[i - 1];
  }
  for (int i = e2; i > s2; --i) {
    if (ma[i - 1] > ma[i]) ma[i - 1] = ma[i];
  }
  for (int i = s1; i <= flag; ++i) {
    if (i + k + 1 <= flag) ans = min(ans, mi[i] + ma[i + k + 1]);
  }
  if (ans >= ans1)
    puts("-1");
  else
    cout << ans << "\n";
  return 0;
}
