#include <bits/stdc++.h>
#pragma comment(linker, "/STACK:10240000")
using namespace std;
const int MAXN = 100010;
struct tnode {
  int d, f, t;
  long long c;
} a[MAXN];
int sta[MAXN][2];
long long all[MAXN][2], times[MAXN][2];
bool cmp(tnode a, tnode b) { return a.d < b.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].f, &a[i].t, &a[i].c);
  }
  memset(times, -1, sizeof(times));
  int cnt0 = 0, cnt1 = 0, num = 0;
  sort(a + 1, a + m + 1, cmp);
  for (int i = m; i >= 1; i--) {
    if (!a[i].f) {
      if (times[a[i].t][0] == -1) {
        times[a[i].t][0] = a[i].c;
        num++;
        if (num == n) {
          cnt0++;
          all[cnt0][0] = 0;
          for (int j = 1; j <= n; j++) {
            all[cnt0][0] += times[j][0];
          }
          sta[cnt0][0] = a[i].d;
        }
      } else if (a[i].c < times[a[i].t][0]) {
        if (num == n) {
          cnt0++;
          all[cnt0][0] = all[cnt0 - 1][0] - (times[a[i].t][0] - a[i].c);
          sta[cnt0][0] = a[i].d;
        }
        times[a[i].t][0] = a[i].c;
      }
    }
  }
  num = 0;
  for (int i = 1; i <= m; i++) {
    if (!a[i].t) {
      if (times[a[i].f][1] == -1) {
        times[a[i].f][1] = a[i].c;
        num++;
        if (num == n) {
          cnt1++;
          all[cnt1][1] = 0;
          for (int j = 1; j <= n; j++) {
            all[cnt1][1] += times[j][1];
          }
          sta[cnt1][1] = a[i].d;
        }
      } else if (a[i].c < times[a[i].f][1]) {
        if (num == n) {
          cnt1++;
          all[cnt1][1] = all[cnt1 - 1][1] - (times[a[i].f][1] - a[i].c);
          sta[cnt1][1] = a[i].d;
        }
        times[a[i].f][1] = a[i].c;
      }
    }
  }
  bool flag = false;
  long long ans = -1;
  int j = cnt0;
  if (j) {
    for (int i = 1; i <= cnt1; i++) {
      while (sta[j][0] - sta[i][1] <= k) {
        j--;
        if (j == 0) {
          break;
        }
      }
      if (!j) {
        break;
      }
      if ((ans == -1) || (all[i][1] + all[j][0] < ans)) {
        ans = all[i][1] + all[j][0];
        flag = true;
      }
    }
  }
  if (!flag) {
    printf("-1\n");
  } else {
    printf("%I64d\n", ans);
  }
  return 0;
}
