#include <bits/stdc++.h>
using namespace std;
const int MAXN = 1000006;
const long long int INF = 100000000000000000ll;
vector<pair<int, int> > G1[MAXN], G2[MAXN];
int w1[MAXN], w2[MAXN];
long long int ans1[MAXN], ans2[MAXN];
int main(int argc, char const *argv[]) {
  int n, m, k;
  scanf("%d %d %d", &n, &m, &k);
  for (int i = 0; i < m; ++i) {
    int d, u, v, w;
    scanf("%d %d %d %d", &d, &u, &v, &w);
    if (u == 0) {
      G2[d].push_back(pair<int, int>(v, w));
    } else {
      G1[d].push_back(pair<int, int>(u, w));
    }
  }
  memset(w1, -1, sizeof w1);
  int ctr1 = 0;
  long long int curr_cost1 = 0;
  ans1[0] = INF;
  for (int i = 1; i < MAXN; ++i) {
    for (int j = 0; j < G1[i].size(); ++j) {
      int src = G1[i][j].first, wt = G1[i][j].second;
      if (w1[src] == -1) {
        w1[src] = wt;
        ctr1++;
        curr_cost1 += wt;
      } else {
        if (wt < w1[src]) {
          curr_cost1 -= w1[src];
          w1[src] = wt;
          curr_cost1 += w1[src];
        }
      }
    }
    if (ctr1 == n)
      ans1[i] = curr_cost1;
    else
      ans1[i] = INF;
    ans1[i] = min(ans1[i - 1], ans1[i]);
  }
  memset(w2, -1, sizeof w2);
  int ctr2 = 0;
  long long int curr_cost2 = 0;
  ans2[MAXN - 1] = INF;
  for (int i = MAXN - 2; i >= 0; --i) {
    for (int j = 0; j < G2[i].size(); ++j) {
      int src = G2[i][j].first, wt = G2[i][j].second;
      if (w2[src] == -1) {
        w2[src] = wt;
        ctr2++;
        curr_cost2 += wt;
      } else {
        if (wt < w2[src]) {
          curr_cost2 -= w2[src];
          w2[src] = wt;
          curr_cost2 += w2[src];
        }
      }
    }
    if (ctr2 == n)
      ans2[i] = curr_cost2;
    else
      ans2[i] = INF;
    ans2[i] = min(ans2[i + 1], ans2[i]);
  }
  long long int fans = INF;
  for (int i = 1; i + k < MAXN; ++i) {
    fans = min(fans, ans1[i - 1] + ans2[i + k]);
  }
  if (fans >= INF) fans = -1;
  printf("%lld\n", fans);
  return 0;
}
