#include <bits/stdc++.h>
using namespace std;
vector<pair<int, int> > f[100005], t[100005];
vector<int> fmx[100005], tmx[100005];
int ptf[100005] = {}, ptt[100005] = {};
vector<int> goingt;
int main() {
  int n, m, k;
  scanf("%d%d%d", &n, &m, &k);
  while (m--) {
    int d, fx, tx, c;
    scanf("%d%d%d%d", &d, &fx, &tx, &c);
    if (tx == 0) {
      f[fx].push_back({d, c});
      goingt.push_back(d + 1);
    } else {
      t[tx].push_back({d, c});
    }
  }
  sort(goingt.begin(), goingt.end());
  goingt.resize(distance(goingt.begin(), unique(goingt.begin(), goingt.end())));
  for (int i = 1; i <= n; i++) {
    if (f[i].empty() || t[i].empty()) {
      cout << -1 << endl;
      return 0;
    }
    sort(f[i].begin(), f[i].end());
    fmx[i].resize(f[i].size());
    fmx[i][0] = f[i][0].second;
    for (int j = 1; j < f[i].size(); j++) {
      fmx[i][j] = min(f[i][j].second, fmx[i][j - 1]);
    }
    sort(t[i].begin(), t[i].end());
    tmx[i].resize(t[i].size());
    tmx[i].back() = t[i].back().second;
    for (int j = t[i].size() - 2; j >= 0; j--) {
      tmx[i][j] = min(t[i][j].second, tmx[i][j + 1]);
    }
  }
  long long ans = 1e15;
  for (int i = 0; i < goingt.size(); i++) {
    int l = goingt[i];
    int r = goingt[i] + k - 1;
    bool flag = 1;
    long long ctrip = 0;
    for (int j = 1; j <= n; j++) {
      while (ptf[j] < f[j].size() && f[j][ptf[j]].first < l) {
        ptf[j]++;
      }
      if (ptf[j] == 0) {
        flag = 0;
        break;
      }
      ptf[j]--;
      if (f[j][ptf[j]].first < l) {
        ctrip += fmx[j][ptf[j]];
      } else {
        flag = 0;
        break;
      }
      while (ptt[j] < t[j].size() && t[j][ptt[j]].first <= r) {
        ptt[j]++;
      }
      if (ptt[j] == t[j].size()) {
        ptt[j]--;
        flag = 0;
        break;
      }
      if (t[j][ptt[j]].first > r) {
        ctrip += tmx[j][ptt[j]];
      } else {
        flag = 0;
        break;
      }
    }
    if (flag) {
      ans = min(ans, ctrip);
    }
  }
  if (ans == 1e15) {
    cout << -1 << endl;
    return 0;
  }
  cout << ans << endl;
  return 0;
}
