#include <bits/stdc++.h>
using namespace std;
const int maxn = 1e5 + 10;
const int D = 1e6;
const long long INF = 1e18;
int n, m, k;
priority_queue<pair<int, int> > Q[maxn];
vector<pair<int, int> > in[D + 10];
vector<int> out[D + 10];
long long cost[maxn];
long long ans = INF;
void solve() {
  int count = 0;
  long long sum = 0;
  for (int x = 1; x <= n; ++x) {
    while (!Q[x].empty() && Q[x].top().second < k) Q[x].pop();
    if (Q[x].empty()) return;
    sum -= Q[x].top().first;
  }
  for (int d = 1; d <= D; ++d) {
    for (auto i : in[d - 1]) {
      int c = i.first;
      int id = i.second;
      if (!cost[id] || c < cost[id]) {
        if (!cost[id]) ++count;
        sum -= cost[id];
        sum += c;
        cost[id] = c;
      }
    }
    if (d + k - 1 > D) break;
    for (auto x : out[d + k - 1]) {
      sum += Q[x].top().first;
      while (!Q[x].empty() && Q[x].top().second <= d + k - 1) Q[x].pop();
      if (Q[x].empty()) return;
      sum -= Q[x].top().first;
    }
    if (count == n) ans = min(ans, sum);
  }
}
int main() {
  scanf("%d %d %d", &n, &m, &k);
  for (int i = 1; i <= m; ++i) {
    int d, f, t, c;
    scanf("%d %d %d %d", &d, &f, &t, &c);
    if (!t)
      in[d].push_back({c, f});
    else {
      Q[t].push({-c, d});
      out[d].push_back(t);
    }
  }
  solve();
  if (ans == INF) ans = -1;
  printf("%lld\n", ans);
  return 0;
}
