#include <bits/stdc++.h>
using namespace std;
inline int mini(int a, int b) { return (a > b) ? b : a; }
inline int maxi(int a, int b) { return (a < b) ? b : a; }
vector<pair<int, int> > to[100010], bak[100010];
int tos[100010], bas[100010];
long long pre[1000010], suf[1000010];
int ear, lat = 100000000;
int main(void) {
  int n, m, k;
  scanf("%d%d%d", &n, &m, &k);
  for (int i = 1; i <= m; i++) {
    int tt, ff, dd, cc;
    scanf("%d%d%d%d", &tt, &ff, &dd, &cc);
    if (ff) {
      to[ff].push_back(make_pair(tt, cc));
    } else {
      bak[dd].push_back(make_pair(tt, cc));
    }
  }
  for (int i = 1; i <= n; i++) {
    sort(to[i].begin(), to[i].end());
    sort(bak[i].begin(), bak[i].end());
    tos[i] = to[i].size();
    bas[i] = bak[i].size();
    if (to[i].empty() || bak[i].empty()) {
      printf("-1");
      return 0;
    }
    ear = maxi(ear, to[i][0].first + 1);
    lat = mini(lat, bak[i][bas[i] - 1].first - k);
  }
  if (ear > lat) {
    printf("-1");
    return 0;
  }
  for (int i = 1; i <= n; i++) {
    int mn = 10000000;
    int j = 0;
    while (j < tos[i] && to[i][j].first < ear) {
      mn = mini(mn, to[i][j].second);
      j++;
    }
    pre[ear] += mn;
    while (j < tos[i] && to[i][j].first < lat) {
      pre[to[i][j].first + 1] -= mn;
      mn = mini(mn, to[i][j].second);
      pre[to[i][j].first + 1] += mn;
      j++;
    }
    mn = 100000000;
    j = bas[i] - 1;
    while (~j && bak[i][j].first - k >= lat) {
      mn = mini(mn, bak[i][j].second);
      j--;
    }
    suf[lat] += mn;
    while (~j && bak[i][j].first - k >= ear) {
      suf[bak[i][j].first - k] -= mn;
      mn = mini(mn, bak[i][j].second);
      suf[bak[i][j].first - k] += mn;
      j--;
    }
  }
  long long res = 1ll << 60, ans = 0;
  for (int i = ear; i <= lat; i++) {
    ans += suf[i];
  }
  for (int i = ear; i <= lat; i++) {
    ans += pre[i];
    res = min(res, ans);
    ans -= suf[i];
  }
  printf("%I64d", res);
  return 0;
}
