#include <bits/stdc++.h>
using namespace std;
const int maxn = 1e6 + 5;
int n, m, k;
struct F {
  int u, cost;
};
vector<F> to0[maxn], left0[maxn];
int d, u, v, cost, mxt;
long long mn[maxn];
long long arr[maxn], dep[maxn];
int main() {
  scanf("%d%d%d", &n, &m, &k);
  for (int i = 1; i <= m; ++i) {
    scanf("%d%d%d%d", &d, &u, &v, &cost);
    mxt = max(mxt, d);
    if (u)
      to0[d].push_back((F){u, cost});
    else
      left0[d].push_back((F){v, cost});
  }
  for (int i = 1; i <= n; ++i) {
    mn[i] = 1000000000000ll;
    arr[0] += mn[i];
    dep[mxt + 1] += mn[i];
  }
  for (int i = 1; i <= mxt; ++i) {
    arr[i] = arr[i - 1];
    int l = to0[i].size();
    for (int j = 0; j < l; ++j) {
      int nu = to0[i][j].u;
      if (to0[i][j].cost < mn[nu])
        arr[i] -= mn[nu], arr[i] += to0[i][j].cost, mn[nu] = to0[i][j].cost;
    }
  }
  for (int i = 1; i <= n; ++i) mn[i] = 1000000000000ll;
  for (int i = mxt; i >= 1; --i) {
    dep[i] = dep[i + 1];
    int l = left0[i].size();
    for (int j = 0; j < l; ++j) {
      int nv = left0[i][j].u;
      if (left0[i][j].cost < mn[nv])
        dep[i] -= mn[nv], dep[i] += left0[i][j].cost, mn[nv] = left0[i][j].cost;
    }
  }
  long long ans = 0x3f3f3f3f3f3f3f3f;
  for (int i = 1; i <= mxt - k - 1; ++i) {
    ans = min(ans, arr[i] + dep[i + k + 1]);
  }
  if (ans > 1e11)
    puts("-1");
  else
    printf("%lld", ans);
  return 0;
}
