#include <bits/stdc++.h>
using namespace std;
const int N = 100005;
struct task {
  int d, t, f, c;
};
bool comp(task a, task b) { return a.d < b.d; }
task a[N];
int mi[N];
long long dp1[30 * N], dp2[30 * N];
int main() {
  int n, m, k, i, j, c = 0;
  scanf("%d%d%d", &n, &m, &k);
  for (i = 0; i < m; i++) {
    scanf("%d%d%d%d", &a[i].d, &a[i].f, &a[i].t, &a[i].c);
  }
  sort(a, a + m, comp);
  j = 0;
  long long ans = 0;
  memset(mi, -1, sizeof(mi));
  memset(dp1, -1, sizeof(dp1));
  memset(dp2, -1, sizeof(dp2));
  for (i = 0; i <= 1000000; i++) {
    while (j < m && a[j].d <= i) {
      if (a[j].t == 0) {
        if (mi[a[j].f] == -1) {
          mi[a[j].f] = a[j].c;
          c++;
          ans += a[j].c;
        }
        if (mi[a[j].f] > a[j].c) {
          ans -= mi[a[j].f];
          mi[a[j].f] = a[j].c;
          ans += a[j].c;
        }
      }
      j++;
    }
    if (c == n) dp1[i] = ans;
  }
  j = m - 1;
  c = 0;
  ans = 0;
  memset(mi, -1, sizeof(mi));
  for (i = 1000000; i >= 0; i--) {
    while (j >= 0 && a[j].d >= i) {
      if (a[j].f == 0) {
        if (mi[a[j].t] == -1) {
          mi[a[j].t] = a[j].c;
          ans += a[j].c;
          c++;
        }
        if (mi[a[j].t] > a[j].c) {
          ans += a[j].c - mi[a[j].t];
          mi[a[j].t] = a[j].c;
        }
      }
      j--;
    }
    if (c == n) dp2[i] = ans;
  }
  ans = -1;
  for (i = 1; i <= 1000000; i++) {
    if (dp1[i - 1] != -1 && dp2[i + k] != -1) {
      if (ans == -1 || ans > dp1[i - 1] + dp2[i + k])
        ans = dp1[i - 1] + dp2[i + k];
    }
  }
  printf("%lld", ans);
}
