#include <bits/stdc++.h>
using namespace std;
const int MAX = 1 << 20;
const long long INF = 1e12;
int dan[MAX], poc[MAX], kraj[MAX], cost[MAX];
long long pref[MAX], suf[MAX];
vector<pair<int, int> > Tamo[MAX], Nazad[MAX];
int nope() {
  printf("-1\n");
  exit(0);
}
int main() {
  int n, m, k;
  scanf("%d%d%d", &n, &m, &k);
  for (int i = 0; i < m; i++) {
    scanf("%d%d%d%d", &dan[i], &poc[i], &kraj[i], &cost[i]);
    if (poc[i] == 0)
      Nazad[kraj[i]].push_back(pair<int, int>(dan[i], cost[i]));
    else
      Tamo[poc[i]].push_back(pair<int, int>(dan[i], cost[i]));
  }
  for (int i = (1); i < (n + 1); i++) {
    sort(Tamo[i].begin(), Tamo[i].end());
    sort(Nazad[i].begin(), Nazad[i].end(), greater<pair<int, int> >());
    if (Tamo[i].empty()) nope();
    if (Nazad[i].empty()) nope();
    long long minn = INF;
    pref[0] += minn;
    for (auto it : Tamo[i]) {
      if (it.second < minn) pref[it.first + 1] += it.second - minn;
      minn = min(minn, (long long)it.second);
    }
    minn = INF;
    suf[MAX - 1] += minn;
    for (auto it : Nazad[i]) {
      if (it.second < minn) suf[it.first - 1] += it.second - minn;
      minn = min(minn, (long long)it.second);
    }
  }
  for (int i = (1); i < (MAX); i++) pref[i] += pref[i - 1];
  for (int i = MAX - 2; i >= 0; i--) suf[i] += suf[i + 1];
  long long rje = INF;
  for (int p = (1); p < (MAX); p++) {
    int kr = p + k - 1;
    if (kr >= MAX) break;
    rje = min(rje, pref[p] + suf[kr]);
  }
  if (rje >= INF) nope();
  cout << rje << endl;
  return 0;
}
