#include <bits/stdc++.h>
using namespace std;
const int N = 100005;
const int M = 1000000;
vector<array<int, 2> > fin[M + 1], fout[M + 1];
long long costin[M + 1], costout[M + 1];
int cost[N];
int main() {
  ios::sync_with_stdio(false);
  cin.tie(NULL);
  int n, m, k;
  cin >> n >> m >> k;
  for (int i = 1; i <= m; i++) {
    int d, f, t, c;
    cin >> d >> f >> t >> c;
    if (f == 0)
      fin[d].push_back({t, c});
    else
      fout[d].push_back({f, c});
  }
  {
    int cnt = 0;
    bool flg = false;
    costin[0] = -1;
    memset(cost, -1, sizeof(cost));
    for (int d = 1; d <= M; d++) {
      costin[d] = costin[d - 1];
      for (auto x : fout[d]) {
        if (cost[x[0]] == -1) {
          cost[x[0]] = x[1];
          cnt++;
        } else if (cost[x[0]] > x[1]) {
          if (flg) {
            costin[d] -= cost[x[0]];
            costin[d] += x[1];
          }
          cost[x[0]] = x[1];
        }
      }
      if (cnt == n && !flg) {
        flg = true;
        costin[d] = 0;
        for (int i = 1; i <= n; i++) {
          costin[d] += cost[i];
        }
      }
    }
  }
  {
    int cnt = 0;
    bool flg = false;
    costout[M + 1] = -1;
    memset(cost, -1, sizeof(cost));
    for (int d = M; d >= 1; d--) {
      costout[d] = costout[d + 1];
      for (auto x : fin[d]) {
        if (cost[x[0]] == -1) {
          cost[x[0]] = x[1];
          cnt++;
        } else if (cost[x[0]] > x[1]) {
          if (flg) {
            costout[d] -= cost[x[0]];
            costout[d] += x[1];
          }
          cost[x[0]] = x[1];
        }
      }
      if (cnt == n && !flg) {
        flg = true;
        costout[d] = 0;
        for (int i = 1; i <= n; i++) {
          costout[d] += cost[i];
        }
      }
    }
  }
  long long ans = -1;
  for (int d = 1; d + k + 1 <= M; d++) {
    if (costin[d] == -1 || costout[d + k + 1] == -1) continue;
    if (ans == -1) ans = costin[d] + costout[d + k + 1];
    ans = min(ans, costin[d] + costout[d + k + 1]);
  }
  cout << ans << '\n';
  return 0;
}
