#include <bits/stdc++.h>
using namespace std;
const int Maxn = 1e6 + 10;
struct node {
  long long num, t, c;
};
bool cmp1(node a, node b) { return a.t < b.t; }
bool cmp2(node a, node b) { return a.t > b.t; }
long long l[Maxn] = {}, r[Maxn] = {}, f[Maxn] = {}, vis1[Maxn] = {},
          vis2[Maxn] = {};
vector<node> a, b;
int main() {
  long long n, m, k, ft = -1, lt = -1;
  cin >> n >> m >> k;
  for (int i = 1; i <= m; i++) {
    int x, y, z, w;
    node N;
    scanf("%d%d%d%d", &x, &y, &z, &w);
    N.c = w;
    N.t = x;
    if (z == 0) {
      N.num = y;
      a.push_back(N);
    } else {
      N.num = z;
      b.push_back(N);
    }
  }
  sort(a.begin(), a.end(), cmp1);
  sort(b.begin(), b.end(), cmp2);
  long long sum = 0, cnt = 0, nt = -1;
  for (int i = 0; i < a.size(); i++) {
    int x = a[i].num;
    while (nt != -1 && nt < a[i].t) {
      nt++;
      l[nt] = sum;
    }
    if (!vis1[x]) {
      vis1[x] = a[i].c;
      cnt++;
      sum += a[i].c;
    } else {
      if (vis1[x] > a[i].c) {
        sum += a[i].c - vis1[x];
        vis1[x] = a[i].c;
        l[nt] = sum;
      }
    }
    if (cnt == n && ft == -1) {
      ft = a[i].t;
      nt = ft;
      l[ft] = sum;
    }
  }
  if (nt != -1)
    for (int i = nt + 1; i <= 1e6; i++) l[i] = l[i - 1];
  sum = 0, cnt = 0, nt = -1;
  for (int i = 0; i < b.size(); i++) {
    int x = b[i].num;
    while (nt != -1 && nt > b[i].t) {
      nt--;
      r[nt] = sum;
    }
    if (!vis2[x]) {
      vis2[x] = b[i].c;
      cnt++;
      sum += b[i].c;
    } else {
      if (vis2[x] > b[i].c) {
        sum += b[i].c - vis2[x];
        vis2[x] = b[i].c;
        r[nt] = sum;
      }
    }
    if (cnt == n && lt == -1) {
      nt = b[i].t;
      lt = nt;
      r[lt] = sum;
    }
  }
  if (nt != -1)
    for (int i = nt - 1; i >= 0; i--) r[i] = r[i + 1];
  long long ans = 1e15;
  if (ft != -1 && lt != -1)
    for (int i = ft; i + k + 1 <= lt; i++) {
      ans = min(ans, l[i] + r[i + k + 1]);
    }
  if (ans == 1e15)
    cout << -1 << endl;
  else
    cout << ans << endl;
  return 0;
}
