#include <bits/stdc++.h>
using namespace std;
struct Node {
  int city, cos;
  Node() {}
  Node(int _city, int _cos) : city(_city), cos(_cos) {}
};
vector<Node> fl[1001000][2];
int mn[100100];
int mx[100100];
int pre[100100];
int suf[100100];
long long presum[1001000];
long long sufsum[1001000];
int main() {
  int n, m, k, d, f, t, c;
  scanf("%d %d %d", &n, &m, &k);
  for (int i = 0; i < m; ++i) {
    scanf("%d %d %d %d", &d, &f, &t, &c);
    if (f != 0) {
      fl[d][0].push_back(Node(f, c));
      if (mn[f] == 0)
        mn[f] = d;
      else
        mn[f] = min(mn[f], d);
    } else {
      fl[d][1].push_back(Node(t, c));
      if (mx[t] == 0)
        mx[t] = d;
      else
        mx[t] = max(mx[t], d);
    }
  }
  if (m < 2 * n)
    printf("-1\n");
  else {
    for (int i = 1; i < 1001000; ++i) {
      for (int j = 0; j < fl[i][0].size(); ++j) {
        Node &tmp = fl[i][0][j];
        if (pre[tmp.city] == 0) {
          pre[tmp.city] = tmp.cos;
          presum[i] += tmp.cos;
        } else if (pre[tmp.city] > tmp.cos) {
          presum[i] -= pre[tmp.city];
          pre[tmp.city] = tmp.cos;
          presum[i] += tmp.cos;
        }
      }
      presum[i] += presum[i - 1];
    }
    for (int i = 1001000 - 2; i; i--) {
      for (int j = 0; j < fl[i][1].size(); ++j) {
        Node &tmp = fl[i][1][j];
        if (suf[tmp.city] == 0) {
          suf[tmp.city] = tmp.cos;
          sufsum[i] += tmp.cos;
        } else if (suf[tmp.city] > tmp.cos) {
          sufsum[i] -= suf[tmp.city];
          suf[tmp.city] = tmp.cos;
          sufsum[i] += tmp.cos;
        }
      }
      sufsum[i] += sufsum[i + 1];
    }
    int st = 0, en = 1001000, flg = 1;
    for (int i = 1; i <= n; ++i) {
      st = max(st, mn[i]);
      en = min(en, mx[i]);
      if (mn[i] == 0 || mx[i] == 0) flg = 0;
    }
    if (en - st - 1 < k || !flg)
      printf("-1\n");
    else {
      long long ans = 1e18;
      for (int i = st; i + k < en; ++i)
        ans = min(ans, presum[i] + sufsum[i + k + 1]);
      printf("%I64d\n", ans);
    }
  }
}
