#include <bits/stdc++.h>
using namespace std;
const int maxn = 1000000 + 10;
const long long INF = 200000000000LL;
int n, m, k;
vector<pair<int, int> > in[maxn], out[maxn];
long long pre[maxn], suf[maxn];
long long minc[100000 + 10];
int main() {
  scanf("%d%d%d", &n, &m, &k);
  int maxd = 1;
  for (int i = 0; i < m; i++) {
    int d, f, t, c;
    scanf("%d%d%d%d", &d, &f, &t, &c);
    if (!f)
      out[d].push_back(make_pair(t, c));
    else
      in[d].push_back(make_pair(f, c));
    if (d > maxd) maxd = d;
  }
  for (int i = 1; i < n + 1; i++) minc[i] = INF;
  long long tot = INF * n;
  for (int i = 1; i < maxd + 1; i++) {
    for (pair<int, int> x : in[i]) {
      if (x.second < minc[x.first]) {
        tot -= minc[x.first] - x.second;
        minc[x.first] = x.second;
      }
    }
    pre[i] = tot;
  }
  for (int i = 1; i < n + 1; i++) minc[i] = INF;
  tot = INF * n;
  for (int i = maxd + 1 - 1; i >= 1; i--) {
    for (pair<int, int> x : out[i]) {
      if (x.second < minc[x.first]) {
        tot -= minc[x.first] - x.second;
        minc[x.first] = x.second;
      }
    }
    suf[i] = tot;
  }
  long long ans = INF * n;
  for (int i = 1; i + k + 1 <= maxd; i++) {
    ans = min(ans, pre[i] + suf[i + k + 1]);
  }
  if (ans >= INF)
    printf("-1\n");
  else
    printf("%lld\n", ans);
  return 0;
}
