#include <bits/stdc++.h>
using namespace std;
const int N = 100002;
int n, m, k, currentOutCost[N], cntOut, cntIn;
struct flight {
  int i, d, c;
} in[N], out[N];
multiset<int> a[N];
bool cmp(flight x, flight y) { return x.d < y.d; }
int main() {
  scanf("%d%d%d", &n, &m, &k);
  for (int i = (1); i <= (int)(m); ++i) {
    int d, first, t, c;
    scanf("%d%d", &d, &first);
    scanf("%d%d", &t, &c);
    if (first)
      out[++cntOut] = {first, d, c};
    else
      in[++cntIn] = {t, d, c};
  }
  sort(out + 1, out + 1 + cntOut, cmp);
  sort(in + 1, in + 1 + cntIn, cmp);
  long long ans = 1000000000000000000ll, currOut = 0, currInSum = 0,
            currOutSum = 0, j = 1;
  for (int i = (1); i <= (int)(cntIn); ++i) a[in[i].i].insert(in[i].c);
  for (int i = (1); i <= (int)(n); ++i)
    if (((int)(a[i]).size()))
      currInSum += *a[i].begin();
    else
      return cout << -1, 0;
  for (int i = (1); i <= (int)(cntOut); ++i) {
    int node = out[i].i, d = out[i].d, c = out[i].c;
    while (j <= cntIn and in[j].d <= d + k) {
      currInSum -= *a[in[j].i].begin();
      a[in[j].i].erase(a[in[j].i].find(in[j].c));
      if (!((int)(a[in[j].i]).size())) goto fn;
      currInSum += *a[in[j].i].begin();
      ++j;
    }
    if (!currentOutCost[node]) {
      ++currOut;
      currInSum += currentOutCost[node] = c;
    } else {
      currInSum -= currentOutCost[node];
      currentOutCost[node] = min(currentOutCost[node], c);
      currInSum += currentOutCost[node];
    }
    if (currOut == n) ans = min(ans, currOutSum + currInSum);
  }
fn:
  cout << (ans == 1000000000000000000ll ? -1 : ans);
}
