#include <bits/stdc++.h>
using namespace std;
const int N = 1e6;
int n, m, k;
vector<pair<int, int> > in[N + 10], out[N + 10];
long long f1[N + 10], f2[N + 10];
int num1[N + 10], num2[N + 10];
int mi[N + 10], MI[N + 10];
int main() {
  ios::sync_with_stdio(0), cin.tie(0);
  cin >> n >> m >> k;
  for (int i = 1; i <= m; i++) {
    int d, f, t, c;
    cin >> d >> f >> t >> c;
    if (t == 0)
      in[d].push_back(make_pair(f, c));
    else {
      out[d].push_back(make_pair(t, c));
    }
  }
  for (int i = 1; i <= N; i++) {
    num1[i] = num1[i - 1];
    f1[i] = f1[i - 1];
    for (int j = 0; j <= (int)in[i].size() - 1; j++) {
      int from = in[i][j].first, cost = in[i][j].second;
      if (mi[from] == 0) {
        mi[from] = cost;
        num1[i]++;
        f1[i] += cost;
      } else {
        if (mi[from] > cost) {
          f1[i] -= (mi[from] - cost);
          mi[from] = cost;
        }
      }
    }
  }
  for (int i = N; i >= 1; i--) {
    f2[i] = f2[i + 1];
    num2[i] = num2[i + 1];
    for (int j = 0; j <= (int)out[i].size() - 1; j++) {
      int to = out[i][j].first;
      int cost = out[i][j].second;
      if (MI[to] == 0) {
        MI[to] = cost;
        f2[i] += cost;
        num2[i]++;
      } else {
        if (MI[to] > cost) {
          f2[i] -= (MI[to] - cost);
          MI[to] = cost;
        }
      }
    }
  }
  long long ans = -1;
  for (int i = 1; i + k + 1 <= N; i++)
    if (num1[i] == n) {
      if (num2[i + k + 1] == n) {
        long long temp = f1[i] + f2[i + k + 1];
        if (ans == -1) {
          ans = temp;
        } else
          ans = min(ans, temp);
      }
    }
  cout << ans << endl;
  return 0;
}
