#include <bits/stdc++.h>
using namespace std;
const long long INF = 1e18 + 10;
const int maxn = 1e6 + 10;
struct node {
  int d, l, r;
  long long c;
} a[maxn];
long long L[maxn], R[maxn], vis[maxn];
bool cmp(node x, node y) { return x.d < y.d; }
int main() {
  int n, m, k;
  scanf("%d%d%d", &n, &m, &k);
  for (int i = 1; i <= m; ++i) {
    scanf("%d%d%d%I64d", &a[i].d, &a[i].l, &a[i].r, &a[i].c);
  }
  sort(a + 1, a + 1 + m, cmp);
  memset(L, -1, sizeof L);
  memset(R, -1, sizeof R);
  memset(vis, 0, sizeof vis);
  long long cnt = 0;
  long long tot = 0;
  for (int i = 1; i <= m; ++i) {
    if (a[i].r != 0) continue;
    if (!vis[a[i].l]) {
      vis[a[i].l] = a[i].c;
      cnt++;
      tot += a[i].c;
    } else {
      if (vis[a[i].l] > a[i].c) {
        tot = tot - vis[a[i].l] + a[i].c;
        vis[a[i].l] = a[i].c;
      }
    }
    if (cnt == n) {
      L[i] = tot;
    }
  }
  memset(vis, 0, sizeof vis);
  cnt = 0;
  tot = 0;
  for (int i = m; i >= 1; --i) {
    if (a[i].l != 0) continue;
    if (!vis[a[i].r]) {
      vis[a[i].r] = a[i].c;
      cnt++;
      tot += a[i].c;
    } else {
      if (vis[a[i].r] > a[i].c) {
        tot = tot - vis[a[i].r] + a[i].c;
        vis[a[i].r] = a[i].c;
      }
    }
    if (cnt == n) {
      R[i] = tot;
    }
  }
  long long ans = INF;
  for (int i = m; i >= 1; --i) {
    if (R[i] == -1) continue;
    if (R[i + 1] != -1) R[i] = min(R[i], R[i + 1]);
  }
  for (int i = 1; i <= m; ++i) {
    if (L[i] == -1) continue;
    int day = a[i].d + k + 1;
    int l = i + 1, r = m, len = 50;
    while (len--) {
      int mid = (l + r) / 2;
      if (a[mid].d >= day)
        r = mid - 1;
      else
        l = mid + 1;
    }
    if (l == -1) continue;
    if (R[l] != -1) {
      ans = min(ans, L[i] + R[l]);
    }
  }
  if (ans == INF) {
    puts("-1");
  } else {
    cout << ans << endl;
  }
}
