#include <bits/stdc++.h>
using namespace std;
const int N = int(2e5) + 5;
const int LN = (int)3e6 + 7;
const int inf = (int)1e9 + 7;
const long long linf = (long long)1e18 + 7;
int n, m, k;
int u[N];
long long mn[N];
int ans[N];
int cnt = 0;
vector<pair<pair<int, int>, int> > here[LN];
long long now = 0;
long long pref[LN], suff[LN];
int main() {
  scanf("%d %d %d", &n, &m, &k);
  for (int i = 1; i <= m; ++i) {
    int d, f, t, c;
    scanf("%d %d %d %d", &d, &f, &t, &c);
    here[d].push_back({{f, t}, c});
  }
  for (int i = 1; i <= n; ++i) {
    mn[i] = linf;
  }
  fill(suff, suff + LN, linf);
  fill(pref, pref + LN, linf);
  for (int i = 1; i <= (int)2e6; ++i) {
    pref[i] = pref[i - 1];
    if (cnt == n) {
      pref[i] = now;
    }
    for (auto j : here[i]) {
      int fr = j.first.first;
      int to = j.first.second;
      if (!to) {
        if (!u[fr]) {
          u[fr] = 1;
          mn[fr] = j.second;
          now += j.second;
          ++cnt;
        } else {
          if (mn[fr] > j.second) {
            now -= mn[fr];
            now += j.second;
            mn[fr] = j.second;
          }
        }
      }
    }
  }
  now = 0;
  cnt = 0;
  for (int i = 1; i <= n; ++i) {
    mn[i] = linf;
    u[i] = 0;
  }
  for (int i = (int)2e6; i >= 1; --i) {
    for (auto j : here[i]) {
      int fr = j.first.first;
      int to = j.first.second;
      if (!fr) {
        if (!u[to]) {
          u[to] = 1;
          mn[to] = j.second;
          now += j.second;
          ++cnt;
        } else {
          if (mn[to] > j.second) {
            now -= mn[to];
            now += j.second;
            mn[to] = j.second;
          }
        }
      }
    }
    suff[i] = suff[i + 1];
    if (cnt == n) {
      suff[i] = now;
    }
  }
  long long ans = linf;
  for (int d = 1; d + k <= (int)2e6; ++d) {
    if (pref[d] != linf && suff[d + k] != linf) {
      if (ans > pref[d] + suff[d + k]) {
        ans = pref[d] + suff[d + k];
      }
    }
  }
  if (ans == linf) {
    printf("-1\n");
    return 0;
  }
  printf("%lld", ans);
  return 0;
}
