#include <bits/stdc++.h>
using namespace std;
struct Node {
  long long d, from, to, val;
} a[250000];
long long vis[250000], l[250000], r[250000];
inline long long cmp(Node p, Node q) { return p.d < q.d; }
int main() {
  long long n, m, k;
  scanf("%I64d%I64d%I64d", &n, &m, &k);
  memset(vis, 0, sizeof vis);
  memset(l, -1, sizeof l);
  memset(r, -1, sizeof r);
  for (int i = 1; i <= m; ++i)
    scanf("%I64d%I64d%I64d%I64d", &a[i].d, &a[i].from, &a[i].to, &a[i].val);
  sort(a + 1, a + m + 1, cmp);
  long long sum = 0, tot = 0;
  for (int i = 1; i <= m; ++i) {
    if (a[i].from == 0) continue;
    if (vis[a[i].from] == 0)
      tot += a[i].val, ++sum, vis[a[i].from] = a[i].val;
    else if (vis[a[i].from] > a[i].val)
      tot -= vis[a[i].from], tot += a[i].val, vis[a[i].from] = a[i].val;
    if (sum == n) l[i] = tot;
  }
  sum = 0, tot = 0;
  memset(vis, 0, sizeof vis);
  for (int i = m; i >= 1; --i) {
    if (a[i].from != 0) continue;
    if (vis[a[i].to] == 0)
      tot += a[i].val, ++sum, vis[a[i].to] = a[i].val;
    else if (vis[a[i].to] > a[i].val)
      tot -= vis[a[i].to], tot += a[i].val, vis[a[i].to] = a[i].val;
    if (sum == n) r[i] = tot;
  }
  long long Ans = 9000000000000;
  for (int i = m; i >= 1; i--)
    if (r[i] == -1)
      continue;
    else 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;
    else {
      long long pos = -1, day = a[i].d + k + 1, ll = i + 1, rr = m;
      while (rr - ll >= 0) {
        long long Mid = rr + ll >> 1;
        if (a[Mid].d >= day)
          rr = Mid - 1, pos = Mid;
        else
          ll = Mid + 1;
      }
      if (pos == -1)
        continue;
      else if (r[pos] != -1)
        Ans = min(Ans, r[pos] + l[i]);
    }
  }
  if (Ans == 9000000000000)
    printf("-1\n");
  else
    printf("%I64d\n", Ans);
  return 0;
}
