#include <bits/stdc++.h>
using namespace std;
stack<int> s[100005];
int n, m, k, from, to, d[100005], f[100005], t[100005], c[100005],
    before[100005], cnt = 0;
bool vis[100005] = {false};
void swap(int &a, int &b) {
  int t = a;
  a = b;
  b = t;
}
void qsort(int l, int r) {
  int i = l, j = r, x = d[(l + r) >> 1];
  do {
    while (d[i] < x) i++;
    while (d[j] > x) j--;
    if (i <= j) {
      swap(d[i], d[j]);
      swap(f[i], f[j]);
      swap(t[i], t[j]);
      swap(c[i], c[j]);
      i++;
      j--;
    }
  } while (i <= j);
  if (l < j) qsort(l, j);
  if (i < r) qsort(i, r);
}
int max(int a, int b) {
  if (a > b) return a;
  return b;
}
int min(int a, int b) {
  if (a < b) return a;
  return b;
}
int main() {
  scanf("%d%d%d", &n, &m, &k);
  from = 0x3f3f3f3f;
  to = 0;
  for (int i = 1; i <= m; i++) {
    scanf("%d%d%d%d", &d[i], &f[i], &t[i], &c[i]);
    from = min(from, d[i]);
    to = max(to, d[i]);
  }
  qsort(1, m);
  for (int i = 1; i <= n; i++) before[i] = 1000005;
  for (int i = m; i > 0; i--) {
    if (f[i] == 0) {
      int top;
      if (!s[t[i]].empty()) top = s[t[i]].top();
      if (s[t[i]].empty() || c[top] > c[i]) s[t[i]].push(i);
    }
  }
  int now = 1, now2 = 1;
  bool flag = true;
  for (int i = 1; i <= n; i++)
    if (s[i].empty()) {
      flag = false;
      break;
    }
  if (!flag) {
    printf("-1\n");
    return 0;
  }
  long long ans, val = 0, qwq;
  for (int i = 1; i <= n; i++) {
    val += 1000005;
    int top = s[i].top();
    val += c[top];
  }
  qwq = 20000000000000;
  ans = qwq;
  for (int start = from - 1; start <= to + 1; start++) {
    if (!flag) break;
    int end = start + k;
    while (now <= m && d[now] < start) {
      if (t[now] == 0) {
        val -= before[f[now]];
        before[f[now]] = min(before[f[now]], c[now]);
        val += before[f[now]];
        if (!vis[f[now]]) cnt++;
        vis[f[now]] = true;
      }
      now++;
    }
    while (now2 <= m && d[now2] < end) {
      if (f[now2] == 0) {
        if (s[t[now2]].empty()) {
          flag = false;
          break;
        }
        int top = s[t[now2]].top();
        if (d[top] < end) {
          val -= c[top];
          s[t[now2]].pop();
          if (!s[t[now2]].empty()) val += c[s[t[now2]].top()];
        }
        if (s[t[now2]].empty()) flag = false;
      }
      now2++;
    }
    if (!flag) break;
    if (cnt == n) ans = min(ans, val);
  }
  if (ans == qwq)
    printf("-1\n");
  else
    printf("%lld\n", ans);
  return 0;
}
