#include <bits/stdc++.h>
using namespace std;
int quick_pow(int a, int b, int MOD) {
  a %= MOD;
  int res = 1;
  while (b) {
    if (b & 1) res = (res * a) % MOD;
    b /= 2;
    a = (a * a) % MOD;
  }
  return res;
}
const int maxn = 200000 + 10;
const int MOD = 1e9 + 7;
struct node {
  int f, t, c;
} s[maxn];
int cmp(const node &x, const node &y) {}
vector<node> vec[1000005];
long long in[1000005], out[1000005];
int vis[maxn];
int main() {
  int i, j, n, m, k;
  scanf("%d%d%d", &n, &m, &k);
  int mx = 0;
  for (i = 1; i <= m; i++) {
    int d;
    scanf("%d%d%d%d", &d, &s[i].f, &s[i].t, &s[i].c);
    vec[d].push_back((node){s[i].f, s[i].t, s[i].c});
    mx = max(mx, d);
  }
  for (i = 1; i <= n; i++) vis[i] = MOD;
  for (i = 0; i <= mx + 1; i++) in[i] = out[i] = 100000000000000000LL;
  int cnt = 0, l = -1, r = -1;
  long long sum = 0;
  for (i = 1; i <= mx; i++) {
    in[i] = in[i - 1];
    if (vec[i].size() == 0) {
      in[i] = in[i - 1];
      continue;
    }
    for (j = 0; j < vec[i].size(); j++) {
      if (vec[i][j].t) continue;
      if (vis[vec[i][j].f] > vec[i][j].c) {
        if (vis[vec[i][j].f] != MOD) {
          sum -= vis[vec[i][j].f] - vec[i][j].c;
        } else {
          cnt++;
          sum += vec[i][j].c;
        }
        vis[vec[i][j].f] = vec[i][j].c;
      }
      if (cnt == n) {
        if (l == -1) l = i;
        in[i] = sum;
      }
    }
  }
  cnt = 0;
  sum = 0;
  for (i = 1; i <= n; i++) vis[i] = MOD;
  for (i = mx; i >= 1; i--) {
    out[i] = out[i + 1];
    if (vec[i].size() == 0) {
      out[i] = out[i + 1];
      continue;
    }
    for (j = 0; j < vec[i].size(); j++) {
      if (vec[i][j].f) continue;
      if (vis[vec[i][j].t] > vec[i][j].c) {
        if (vis[vec[i][j].t] != MOD) {
          sum -= vis[vec[i][j].t] - vec[i][j].c;
        } else {
          cnt++;
          sum += vec[i][j].c;
        }
        vis[vec[i][j].t] = vec[i][j].c;
      }
      if (cnt == n) {
        if (r == -1) r = i;
        out[i] = sum;
      }
    }
  }
  if (r < 0 || l < 0 || r - l <= k) {
    puts("-1");
    return 0;
  }
  long long res = 100000000000000LL;
  for (i = l; i + k + 1 <= r; i++) {
    res = min(res, in[i] + out[i + k + 1]);
  }
  printf("%I64d\n", res);
  return 0;
}
