#include <bits/stdc++.h>
using namespace std;
long long INF = 1e12;
long long pref[1000006], suff[1000009];
long long curr[100003];
vector<pair<int, long long> > go[1000003], back[1000003];
int main() {
  int n, m, k;
  cin >> n >> m >> k;
  for (int i = 1; i <= m; i++) {
    int day, d, a;
    long long c;
    cin >> day >> d >> a >> c;
    if (d == 0)
      back[day].push_back(pair<int, long long>(a, c));
    else
      go[day].push_back(pair<int, long long>(d, c));
  }
  pref[0] = (long long)n * INF;
  suff[1000001] = (long long)n * INF;
  for (int i = 1; i <= n; i++) curr[i] = INF;
  for (int i = 1; i <= 1000000; i++) {
    pref[i] = pref[i - 1];
    for (int j = 0; j < go[i].size(); j++) {
      if (go[i][j].second < curr[go[i][j].first]) {
        pref[i] = pref[i] - curr[go[i][j].first] + go[i][j].second;
        curr[go[i][j].first] = go[i][j].second;
      }
    }
  }
  for (int i = 1; i <= n; i++) curr[i] = INF;
  for (int i = 1000000; i >= 1; i--) {
    suff[i] = suff[i + 1];
    for (int j = 0; j < back[i].size(); j++) {
      if (back[i][j].second < curr[back[i][j].first]) {
        suff[i] = suff[i] - curr[back[i][j].first] + back[i][j].second;
        curr[back[i][j].first] = back[i][j].second;
      }
    }
  }
  long long res = INF;
  for (int i = 1; i + k + 2 <= 1000000; i++) {
    res = min(res, pref[i] + suff[i + k + 1]);
  }
  if (res < INF)
    cout << res << "\n";
  else
    cout << "-1\n";
}
