#include <bits/stdc++.h>
using namespace std;
const int maxn = 1e6 + 1;
const long long inf = 1e18;
int n, m, k;
struct Flight {
  int d, s, t, c;
} f[maxn];
long long mn[maxn], pre[maxn], s;
vector<int> sw[maxn];
int cnt;
int main() {
  ios::sync_with_stdio(0), cin.tie(0);
  cin >> n >> m >> k;
  for (int i = 0; i < m; i++) {
    cin >> f[i].d >> f[i].s >> f[i].t >> f[i].c;
    sw[f[i].d].push_back(i);
  }
  fill(mn + 1, mn + n + 1, inf);
  pre[0] = inf;
  cnt = 0;
  for (int i = 1; i < maxn; i++) {
    for (auto qi : sw[i])
      if (f[qi].t == 0 && f[qi].c < mn[f[qi].s]) {
        if (mn[f[qi].s] == inf)
          cnt++;
        else
          s -= mn[f[qi].s];
        s += (mn[f[qi].s] = f[qi].c);
      }
    pre[i] = cnt == n ? s : inf;
  }
  cerr << pre[2] << '\n';
  s = cnt = 0;
  fill(mn + 1, mn + n + 1, inf);
  long long ans = inf, cur = inf;
  for (int i = maxn - 1; i >= k + 1; i--) {
    for (auto qi : sw[i])
      if (f[qi].s == 0 && f[qi].c < mn[f[qi].t]) {
        if (mn[f[qi].t] == inf)
          cnt++;
        else
          s -= mn[f[qi].t];
        s += (mn[f[qi].t] = f[qi].c);
      }
    cur = min(cur, cnt == n ? s : inf);
    ans = min(ans, cur + pre[i - k - 1]);
  }
  if (ans == inf)
    cout << -1 << '\n';
  else
    cout << ans << '\n';
  return 0;
}
