#include <bits/stdc++.h>
using namespace std;
long long n, m, k, day, dep[1000010], arr[1000010], cost[1000010], cel, from,
    coss;
long long mini[1000010], wylot[1000010], dolot[1000010], sum, inf = 1e7;
vector<pair<long long, int> > tab;
int ptr;
int main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  cin >> n >> m >> k;
  inf *= inf;
  for (int a = 1; a <= m; a++) {
    cin >> day >> dep[a] >> arr[a] >> cost[a];
    tab.push_back(make_pair(day, a));
  }
  sort(tab.begin(), tab.end());
  ptr = 0;
  for (int a = 1; a <= n; a++) mini[a] = inf;
  sum = n * inf;
  dolot[0] = n * inf;
  for (int a = 1; a <= 1e6; a++) {
    while (ptr < tab.size() && tab[ptr].first <= a) {
      cel = arr[tab[ptr].second];
      from = dep[tab[ptr].second];
      coss = cost[tab[ptr].second];
      if (cel != 0) {
        ptr++;
        continue;
      }
      if (coss < mini[from]) {
        sum -= mini[from];
        mini[from] = coss;
        sum += coss;
      }
      ptr++;
    }
    dolot[a] = sum;
  }
  reverse(tab.begin(), tab.end());
  ptr = 0;
  for (int a = 1; a <= n; a++) mini[a] = inf;
  sum = n * inf;
  wylot[(int)1e6 + 1] = n * inf;
  for (int a = 1e6; a >= 0; a--) {
    while (ptr < tab.size() && tab[ptr].first >= a) {
      cel = arr[tab[ptr].second];
      from = dep[tab[ptr].second];
      coss = cost[tab[ptr].second];
      if (cel == 0) {
        ptr++;
        continue;
      }
      if (coss < mini[cel]) {
        sum -= mini[cel];
        mini[cel] = coss;
        sum += coss;
      }
      ptr++;
    }
    wylot[a] = sum;
  }
  long long ans = inf;
  for (int a = 1; a <= 1e6 - k; a++) {
    if (dolot[a - 1] < n * inf && wylot[a + k] < n * inf)
      ans = min(ans, dolot[a - 1] + wylot[a + k]);
  }
  if (ans == inf)
    cout << -1;
  else
    cout << ans << '\n';
  return 0;
}
