#include <bits/stdc++.h>
using namespace std;
struct A {
  int d, f, t, c;
  bool operator<(const A& a) const { return d < a.d; }
};
A v[100005];
int bestLef[100005], bestRig[100005], nxt[100005], pos[100005];
int main() {
  int n, m, k;
  cin >> n >> m >> k;
  for (int i = 1; i <= m; ++i) cin >> v[i].d >> v[i].f >> v[i].t >> v[i].c;
  sort(v + 1, v + m + 1);
  int p = 0;
  int bad = n;
  while (p + 1 <= m && bad) {
    p++;
    if (v[p].t == 0) {
      if (bestLef[v[p].f] == 0) {
        bad--;
        bestLef[v[p].f] = v[p].c;
      } else
        bestLef[v[p].f] = min(bestLef[v[p].f], v[p].c);
    }
  }
  if (bad) {
    cout << "-1";
    return 0;
  }
  int q = m + 1;
  bad = n;
  while (q - 1 > 0 && bad) {
    q--;
    if (v[q].f == 0) {
      if (bestRig[v[q].t] == 0) {
        bad--;
        bestRig[v[q].t] = v[q].c;
      } else
        bestRig[v[q].t] = min(bestRig[v[q].t], v[q].c);
    }
  }
  if (bad || v[q].d - v[p].d - 1 < k) {
    cout << "-1";
    return 0;
  }
  while (v[q - 1].d - v[p].d - 1 >= k) {
    --q;
    if (v[q].f == 0) bestRig[v[q].t] = min(bestRig[v[q].t], v[q].c);
  }
  for (int i = m; i; --i) {
    if (v[i].f != 0) continue;
    nxt[i] = pos[v[i].t];
    if (pos[v[i].t] == 0 || v[i].c < v[pos[v[i].t]].c) pos[v[i].t] = i;
  }
  long long costl = 0, costr = 0;
  for (int i = 1; i <= n; ++i) costl += bestLef[i], costr += bestRig[i];
  long long sol = costl + costr;
  while (q <= m) {
    ++p;
    if (v[p].t == 0) {
      costl -= bestLef[v[p].f];
      bestLef[v[p].f] = min(bestLef[v[p].f], v[p].c);
      costl += bestLef[v[p].f];
    }
    while (q <= m && v[q].d - v[p].d - 1 < k) {
      if (v[q].f == 0) {
        costr -= bestRig[v[q].t];
        bestRig[v[q].t] = v[nxt[q]].c;
        costr += bestRig[v[q].t];
        if (nxt[q] == 0) {
          q = m + 1;
          break;
        }
      }
      q++;
    }
    if (q > m) break;
    sol = min(sol, costl + costr);
  }
  cout << sol;
  return 0;
}
