#include <bits/stdc++.h>
using namespace std;
const int MAXN = 1e5 + 10;
const int MAXD = 1e6 + 10;
const long long INF = 1e16;
struct e {
  int p, c, id;
};
int Bin[MAXN], BinV[MAXN];
int Bout[MAXN];
int N, M, K, mxD = 0, cnt = 0;
priority_queue<pair<int, pair<int, int> > > to[MAXN];
vector<e> Fout[MAXD], Fin[MAXD];
bool possible = true, done = false;
long long ans = INF, cur = 0;
int main() {
  scanf("%d", &N), scanf("%d", &M), scanf("%d", &K);
  for (int i = 0; i < (int)M; i++) {
    int d, first, t, c;
    scanf("%d", &d), scanf("%d", &first), scanf("%d", &t), scanf("%d", &c);
    if (first == 0 && d >= K) {
      to[t].push({-c, {d, i}});
      Fin[d].push_back({t, c, i});
    } else if (t == 0)
      Fout[d].push_back({first, c, i});
    mxD = max(mxD, d);
  }
  for (int i = 1; i < (int)N + 1; i++) {
    if (!to[i].empty()) {
      Bin[i] = to[i].top().second.second;
      BinV[i] = -to[i].top().first;
      cur += BinV[i];
    } else {
      printf("-1\n");
      return 0;
    }
  }
  memset(Bout, -1, sizeof(Bout));
  for (int d = 0; d < (int)mxD + 1; d++) {
    if (d + K - 1 <= mxD)
      for (int i = 0; i < (int)Fin[d + K - 1].size(); i++) {
        int p = Fin[d + K - 1][i].p;
        int c = Fin[d + K - 1][i].c;
        int id = Fin[d + K - 1][i].id;
        if (id == Bin[p]) {
          while (!to[p].empty() && to[p].top().second.first <= d + K - 1)
            to[p].pop();
          if (!to[p].empty()) {
            cur -= BinV[p];
            BinV[p] = -to[p].top().first;
            Bin[p] = to[p].top().second.second;
            cur += BinV[p];
          } else {
            done = true;
            break;
          }
        }
      }
    if (done) break;
    if (cnt == N) {
      ans = min(ans, cur);
    }
    for (int i = 0; i < (int)Fout[d].size(); i++) {
      int p = Fout[d][i].p;
      int c = Fout[d][i].c;
      int id = Fout[d][i].id;
      if (Bout[p] == -1) {
        Bout[p] = c;
        cur += c;
        cnt++;
      } else if (c < Bout[p]) {
        cur -= Bout[p];
        Bout[p] = c;
        cur += Bout[p];
      }
    }
  }
  if (!possible)
    printf("-1\n");
  else
    printf("%lld\n", ans == INF ? -1 : ans);
}
