#include <bits/stdc++.h>
#pragma GCC optimize("O3")
#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx")
using namespace std;
int a, b, c, d, n, m, k;
vector<pair<int, pair<int, int> > > to0, from0;
long long pr[1000002], suf[1000002];
int best[100002];
int main() {
  scanf("%d%d%d", &n, &m, &k);
  for (int _n((m)-1), i(0); i <= _n; i++) {
    scanf("%d%d%d%d", &a, &b, &c, &d);
    --a;
    if (!b) {
      from0.push_back(make_pair(a, make_pair(d, c)));
    } else {
      to0.push_back(make_pair(a, make_pair(d, b)));
    }
  }
  sort((to0).begin(), (to0).end());
  sort((from0).begin(), (from0).end());
  c = 0;
  a = 0;
  long long cur = 0;
  memset(best, -1, sizeof(best));
  for (int _n((1000001) - 1), i(0); i <= _n; i++) {
    while (a < (int)((to0).size()) && to0[a].first < i) {
      int v = to0[a].second.second;
      int cs = to0[a].second.first;
      if (best[v] == -1) {
        ++c;
        best[v] = cs;
        cur += cs;
      } else {
        if (cs < best[v]) {
          cur -= best[v];
          cur += cs;
          best[v] = cs;
        }
      }
      ++a;
    }
    if (c != n) {
      pr[i] = 4LL * 1000000000 * 1000000000;
    } else {
      pr[i] = cur;
    }
  }
  cur = 0;
  memset(best, -1, sizeof(best));
  c = 0;
  a = (int)((from0).size()) - 1;
  for (int i = (1000000), _b = (0); i >= _b; i--) {
    while (a >= 0 && from0[a].first > i) {
      int v = from0[a].second.second;
      int cs = from0[a].second.first;
      if (best[v] == -1) {
        ++c;
        best[v] = cs;
        cur += cs;
      } else {
        if (cs < best[v]) {
          cur -= best[v];
          cur += cs;
          best[v] = cs;
        }
      }
      --a;
    }
    if (c != n) {
      suf[i] = 4LL * 1000000000 * 1000000000;
    } else {
      suf[i] = cur;
    }
  }
  long long ans = 4LL * 1000000000 * 1000000000;
  for (int _n((1000000) - 1), i(0); i <= _n; i++) {
    if (i + k - 1 > 1000000) break;
    long long cur = pr[i] + suf[i + k - 1];
    ans = min(ans, cur);
  }
  if (ans >= 4LL * 1000000000 * 1000000000) ans = -1;
  cout << ans << endl;
}
