#include <bits/stdc++.h>
using namespace std;
int n, m, i, j, l, z, y, k, x;
long long num, sum;
using namespace std;
const long long LLM = 1e18;
const int maxn = 1e6 + 5;
vector<pair<int, int> > fuck2[maxn];
vector<pair<int, int> > fuck1[maxn];
long long c[maxn], a1[maxn], a2[maxn];
long long x1, x2, x3, x4;
int main() {
  scanf("%d%d", &n, &m);
  scanf("%d", &k);
  for (int i = 1; i <= m; i++) {
    scanf("%lld%lld", &x1, &x2);
    scanf("%lld%lld", &x3, &x4);
    if (!x2)
      fuck2[x1].push_back(make_pair(x3, x4));
    else
      fuck1[x1].push_back(make_pair(x2, x4));
  }
  for (int i = 1; i <= 1e6 + 1; i++) {
    a1[i] = LLM;
    a2[i] = LLM;
  }
  for (int i = 1; i <= 1e6 + 1; i++) c[i] = 1e7;
  num = 0;
  sum = (long long)(n) * (1e7);
  for (int i = 1; i <= 1e6 + 1; i++) {
    for (auto x : fuck1[i]) {
      x1 = x.first;
      x2 = x.second;
      if (c[x1] == (1e7)) num++;
      sum -= c[x1];
      c[x1] = min(c[x1], x2);
      sum += c[x1];
    }
    if (num >= n) a1[i] = min(a1[i], sum);
  }
  for (int i = 1; i <= 1e6 + 1; i++) c[i] = 1e7;
  num = 0;
  sum = (long long)(n) * (1e7);
  for (int i = 1e6; i >= 1; i--) {
    for (auto x : fuck2[i]) {
      x1 = x.first;
      x2 = x.second;
      if (c[x1] == (1e7)) num++;
      sum -= c[x1];
      c[x1] = min(c[x1], x2);
      sum += c[x1];
    }
    if (num >= n) a2[i] = min(a2[i], sum);
  }
  long long ans = 5e18;
  for (int i = 1; i <= 1e6; i++)
    if (i + k + 1 <= 1e6 && a1[i] != LLM && a2[i + k + 1] != LLM)
      ans = min(ans, a1[i] + a2[i + k + 1]);
  if (ans == 5e18)
    cout << "-1" << endl;
  else
    cout << ans << endl;
}
