#include <bits/stdc++.h>
using namespace std;
struct flight {
  int d;
  int f;
  int t;
  int c;
};
vector<struct flight> infor;
int pre[100001];
int aft[100001];
long long sum_com[1000001];
long long sum_go[1000001];
int cmp(struct flight x, struct flight y) {
  if (x.d < y.d)
    return 1;
  else
    return 0;
}
int main() {
  int n, m, k;
  scanf("%d%d%d", &n, &m, &k);
  if (m == 0) {
    printf("-1");
    return 0;
  }
  struct flight tem;
  int i;
  for (i = 0; i < m; i++) {
    scanf("%d%d%d%d", &(tem.d), &(tem.f), &(tem.t), &(tem.c));
    infor.push_back(tem);
  }
  sort(infor.begin(), infor.end(), cmp);
  int max_time = (infor[m - 1]).d;
  for (i = 1; i <= n; i++) {
    pre[i] = 10000000;
    aft[i] = 10000000;
  }
  int from;
  int cost;
  int to;
  int day;
  int sig = 0;
  for (i = 0; i < m; i++) {
    cost = (infor[i]).c;
    from = (infor[i]).f;
    day = (infor[i]).d;
    if (from != 0) {
      if (cost < pre[from]) {
        if (pre[from] == 10000000) sig++;
        pre[from] = cost;
      }
      if (sig == n) break;
    }
  }
  long long sum = 0;
  int j;
  for (j = 1; j <= n; j++) {
    sum += pre[j];
  }
  sum_com[day] = sum;
  int p;
  for (i++, p = day + 1; i < m; i++) {
    cost = (infor[i]).c;
    from = (infor[i]).f;
    day = (infor[i]).d;
    if (from != 0) {
      if (cost < pre[from]) {
        while (p < day) sum_com[p++] = sum;
        p++;
        sum = sum - pre[from] + cost;
        sum_com[day] = sum;
        pre[from] = cost;
      }
    }
  }
  while (p <= max_time) sum_com[p++] = sum;
  sig = 0;
  for (i = m - 1; i >= 0; i--) {
    cost = (infor[i]).c;
    to = (infor[i]).t;
    day = (infor[i]).d;
    if (to != 0) {
      if (cost < aft[to]) {
        if (aft[to] == 10000000) sig++;
        aft[to] = cost;
      }
      if (sig == n) break;
    }
  }
  sum = 0;
  for (j = 1; j <= n; j++) {
    sum += aft[j];
  }
  sum_go[day] = sum;
  for (i--, p = day - 1; i >= 0; i--) {
    cost = (infor[i]).c;
    to = (infor[i]).t;
    day = (infor[i]).d;
    if (to != 0) {
      if (cost < aft[to]) {
        while (p > day) sum_go[p--] = sum;
        p--;
        sum = sum - aft[to] + cost;
        sum_go[day] = sum;
        aft[to] = cost;
      }
    }
  }
  while (p >= 1) sum_go[p--] = sum;
  long long min_ = -1;
  for (i = 1; i <= max_time - k - 1; i++) {
    if ((sum_com[i] == 0) || (sum_go[i + k + 1] == 0))
      continue;
    else {
      sum = sum_com[i] + sum_go[i + k + 1];
      if (min_ == -1)
        min_ = sum;
      else if (sum < min_) {
        min_ = sum;
      }
    }
  }
  printf("%I64d", min_);
  return 0;
}
