#include <bits/stdc++.h>
using namespace std;
struct data {
  int day, from, to, cost;
};
bool cmp(data a, data b) { return a.day < b.day; }
data inp[100000 + 7];
long long lft[1000000 + 7], rgt[1000000 + 7];
int city[100000 + 7];
int main() {
  int n, m, k;
  scanf("%d %d %d", &n, &m, &k);
  for (int i = 0; i < m; i++)
    scanf("%d %d %d %d", &inp[i].day, &inp[i].from, &inp[i].to, &inp[i].cost);
  sort(inp, inp + m, cmp);
  int cont = 0, id = 0, tp;
  long long sum = 0;
  lft[0] = 10000000000000LL;
  memset(city, -1, sizeof city);
  for (int i = 1; i <= 1000000; i++) {
    while (id < m && inp[id].day == i) {
      if (inp[id].to == 0) {
        tp = inp[id].from;
        if (city[tp] == -1 || city[tp] > inp[id].cost) {
          if (city[tp] == -1)
            cont++;
          else
            sum -= city[tp];
          city[tp] = inp[id].cost;
          sum += city[tp];
        }
      }
      id++;
    }
    lft[i] = lft[i - 1];
    if (cont == n) lft[i] = min(lft[i], sum);
  }
  memset(city, -1, sizeof city);
  cont = 0;
  sum = 0;
  id = m - 1;
  rgt[1000001] = 10000000000000LL;
  for (int i = 1000000; i > 0; i--) {
    while (id >= 0 && i == inp[id].day) {
      if (inp[id].from == 0) {
        tp = inp[id].to;
        if (city[tp] == -1 || inp[id].cost < city[tp]) {
          if (city[tp] == -1)
            cont++;
          else
            sum -= city[tp];
          sum += inp[id].cost;
          city[tp] = inp[id].cost;
        }
      }
      id--;
    }
    rgt[i] = rgt[i + 1];
    if (cont == n) rgt[i] = min(rgt[i], sum);
  }
  long long fans = 10000000000000LL;
  for (int i = 1; i + k < 1000000; i++)
    fans = min(fans, lft[i] + rgt[i + k + 1]);
  if (fans == 10000000000000LL) fans = -1;
  printf("%lld\n", fans);
  return 0;
}
