#include <bits/stdc++.h>
using namespace std;
const int MAXN = 1e5 + 10;
const int MAXM = 1e5 + 10;
const long long INF = 1e17;
int N, M, K;
long long cur_cost;
int forward_count, backward_count;
int D[MAXM], F[MAXM], T[MAXM], C[MAXM];
pair<int, int> sort_by_date[MAXM];
multiset<int> best_forward[MAXN], best_backward[MAXN];
void input() {
  cin >> N >> M >> K;
  K++;
  for (int i = 1; i <= M; i++) {
    cin >> D[i] >> F[i] >> T[i] >> C[i];
    sort_by_date[i] = {D[i], i};
  }
  sort(sort_by_date + 1, sort_by_date + M + 1);
}
void addForwardFlight(int flightId) {
  if (T[flightId] != 0) return;
  int from = F[flightId];
  int sz = (int)best_forward[from].size();
  if (sz == 0) {
    forward_count++;
    cur_cost += C[flightId];
    best_forward[from].insert(C[flightId]);
  } else {
    int cur_best = *(best_forward[from].begin());
    if (cur_best > C[flightId]) {
      cur_cost += C[flightId] - cur_best;
    }
    best_forward[from].insert(C[flightId]);
  }
}
void addBackwardFlight(int flightId) {
  if (F[flightId] != 0) return;
  int to = T[flightId];
  int sz = (int)best_backward[to].size();
  if (sz == 0) {
    backward_count++;
    cur_cost += C[flightId];
    best_backward[to].insert(C[flightId]);
  } else {
    int cur_best = *(best_backward[to].begin());
    if (cur_best > C[flightId]) {
      cur_cost += C[flightId] - cur_best;
    }
    best_backward[to].insert(C[flightId]);
  }
}
void removeBackwardFlight(int flightId) {
  if (F[flightId] != 0) return;
  int to = T[flightId];
  int sz = (int)best_backward[to].size();
  if (sz == 1) {
    backward_count--;
    cur_cost += -C[flightId];
    best_backward[to].erase(best_backward[to].find(C[flightId]));
  } else if (*(best_backward[to].begin()) == C[flightId]) {
    best_backward[to].erase(best_backward[to].find(C[flightId]));
    int nxt_cost = *best_backward[to].begin();
    cur_cost += nxt_cost - C[flightId];
  } else
    best_backward[to].erase(best_backward[to].find(C[flightId]));
}
long long solve() {
  if (M <= 1) return -1;
  cur_cost = 0, forward_count = 0, backward_count = 0;
  int p1 = 0, p2 = M;
  while (p2 >= 1) {
    addBackwardFlight(sort_by_date[p2].second);
    p2--;
  }
  p2++;
  long long ans = INF;
  while (p1 < M) {
    p1++;
    addForwardFlight(sort_by_date[p1].second);
    if (forward_count != N) continue;
    while (p2 <= M && sort_by_date[p2].first - sort_by_date[p1].first < K) {
      removeBackwardFlight(sort_by_date[p2].second);
      p2++;
    }
    if (p2 > M || sort_by_date[p2].first - sort_by_date[p1].first < K ||
        backward_count != N)
      break;
    ans = min(ans, cur_cost);
  }
  return ans == INF ? -1 : ans;
}
int main() {
  ios::sync_with_stdio(false);
  cin.tie(0);
  input();
  cout << solve();
  return 0;
}
