#include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 5;
const long long inf = 1e15;
struct node {
  int t, x, y;
  long long z;
  node() {}
  node(int _t, int _x, int _y, long long _z) : t(_t), x(_x), y(_y), z(_z) {}
  bool operator<(const node& p) const { return t < p.t; }
} a[N];
long long A[N], B[N], C[N];
int nA[N], nB[N];
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].t, &a[i].x, &a[i].y, &a[i].z);
  }
  sort(a + 1, a + 1 + m);
  int cnt = 0;
  for (int i = 1; i <= m; i++) {
    if (a[i].y == 0) {
      if (!C[a[i].x])
        A[i] = A[i - 1] + a[i].z, cnt++, C[a[i].x] = a[i].z;
      else {
        A[i] = A[i - 1] - C[a[i].x];
        C[a[i].x] = min(C[a[i].x], a[i].z);
        A[i] += C[a[i].x];
      }
    } else {
      A[i] = A[i - 1];
    }
    nA[i] = cnt;
  }
  memset(C, 0, sizeof(C));
  cnt = 0;
  for (int i = m; i >= 1; i--) {
    if (a[i].x == 0) {
      if (!C[a[i].y])
        B[i] = B[i + 1] + a[i].z, cnt++, C[a[i].y] = a[i].z;
      else {
        B[i] = B[i + 1] - C[a[i].y];
        C[a[i].y] = min(C[a[i].y], a[i].z);
        B[i] += C[a[i].y];
      }
    } else {
      B[i] = B[i + 1];
    }
    nB[i] = cnt;
  }
  long long ans = inf;
  for (int i = 1; i <= m; i++) {
    int pos = lower_bound(a + 1, a + 1 + m, node(a[i].t + 1 + k, 0, 0, 0)) - a;
    if (nA[i] != n || nB[pos] != n) continue;
    ans = min(ans, A[i] + B[pos]);
  }
  if (ans >= inf)
    printf("-1\n");
  else
    printf("%I64d\n", ans);
  return 0;
}
