#include <bits/stdc++.h>
using namespace std;
const int N = 100000 + 10;
const int K = 1000000 + 10;
int n, m, k, iin, iout;
vector<pair<int, int> > in[K], out[K];
int mnst[N], mnen[N];
long long st[K], en[K];
int main() {
  scanf("%d %d %d", &n, &m, &k);
  for (int i = 1, d, f, t, c; i <= m; i++) {
    scanf("%d %d %d %d", &d, &f, &t, &c);
    if (f == 0) {
      out[d].push_back(make_pair(t, c));
    } else {
      in[d].push_back(make_pair(f, c));
    }
  }
  memset(mnst, -1, sizeof(mnst));
  long long cur = 0, cnt = 0;
  for (int i = 1; i < K; i++) {
    for (int j = 0; j < in[i].size(); j++) {
      if (mnst[in[i][j].first] == -1) {
        mnst[in[i][j].first] = in[i][j].second;
        cur += in[i][j].second;
        cnt++;
      } else if (in[i][j].second < mnst[in[i][j].first]) {
        cur = cur - mnst[in[i][j].first] + in[i][j].second;
        mnst[in[i][j].first] = in[i][j].second;
      }
    }
    if (cnt == n)
      st[i] = cur;
    else
      st[i] = -1;
  }
  memset(mnen, -1, sizeof(mnen));
  cur = 0, cnt = 0;
  for (int i = K - 1; i; i--) {
    for (int j = 0; j < out[i].size(); j++) {
      if (mnen[out[i][j].first] == -1) {
        mnen[out[i][j].first] = out[i][j].second;
        cur += out[i][j].second;
        cnt++;
      } else if (out[i][j].second < mnen[out[i][j].first]) {
        cur = cur - mnen[out[i][j].first] + out[i][j].second;
        mnen[out[i][j].first] = out[i][j].second;
      }
    }
    if (cnt == n)
      en[i] = cur;
    else
      en[i] = -1;
  }
  long long ans = -1;
  for (int i = 1; i < K; i++) {
    if (st[i] == -1 || i + k + 1 >= K || en[i + k + 1] == -1) continue;
    if (ans == -1)
      ans = st[i] + en[i + k + 1];
    else
      ans = min(ans, st[i] + en[i + k + 1]);
  }
  printf("%lld\n", ans);
}
