#include <bits/stdc++.h>
using namespace std;
const int N = 1e6 + 5;
const int NN = 1e5 + 5;
struct flight {
  long long from, to, cost;
};
vector<vector<flight> > day(N);
vector<multiset<long long> > t7t(NN);
int n, m, k;
long long fo2[NN];
bool vis1[NN], vis2[NN];
int main() {
  scanf("%d%d%d", &n, &m, &k);
  int mx = 0;
  for (int i = 1; i <= m; i++) {
    int d, f, t, c;
    scanf("%d%d%d%d", &d, &f, &t, &c);
    day[d].push_back({f, t, c});
    mx = max(d, mx);
  }
  int cnt1 = 0, cnt2 = 0;
  for (int i = mx; i > k; i--) {
    for (int j = 0; j < day[i].size(); j++) {
      flight F = day[i][j];
      if (F.from != 0) continue;
      t7t[F.to].insert(F.cost);
      if (!vis2[F.to]) {
        cnt2++;
        vis2[F.to] = 1;
      }
    }
  }
  if (cnt2 < n) return puts("-1");
  long long ans2 = 0;
  for (int i = 1; i <= n; i++) {
    ans2 += *t7t[i].begin();
  }
  for (int i = 1; i <= n; i++) fo2[i] = 1e18;
  long long ans = 1e18;
  long long ans1 = 0;
  for (int i = 1; i + k <= mx; i++) {
    for (int j = 0; j < day[i].size(); j++) {
      flight F = day[i][j];
      if (F.to != 0) continue;
      if (!vis1[F.from]) {
        vis1[F.from] = 1;
        cnt1++;
      }
      if (fo2[F.from] != 1e18) ans1 -= fo2[F.from];
      fo2[F.from] = min(fo2[F.from], F.cost);
      ans1 += fo2[F.from];
    }
    bool b = 0;
    for (int j = 0; j < day[i + k].size(); j++) {
      flight F = day[i + k][j];
      if (F.from != 0) continue;
      ans2 -= *t7t[F.to].begin();
      t7t[F.to].erase(t7t[F.to].find(F.cost));
      if (t7t[F.to].empty()) {
        b = 1;
        break;
      }
      ans2 += *t7t[F.to].begin();
    }
    if (b) break;
    if (cnt1 < n || cnt2 < n) continue;
    ans = min(ans1 + ans2, ans);
  }
  if (ans == 1e18)
    printf("-1");
  else
    cout << ans;
  return 0;
}
